Count occurrences of a sub-string with one variable character

Given two strings a and b, and an integer k which is the index in b at which the character can be changed to any other character, the task is to check if b is a sub-string in a and print out how many times b occurs in a in total after replacing the b[k] with every possible lowercase character of English alphabet. Examples:

Input: a = “feeds”, b = “ee”, k = 1
Output: 1 Replace b[1] with ‘k’ and “ed” is a sub-string in “feeds” “ee” is also a sub-string in “feeds” Hence the total count is 2
Input: a = “dogdog”, b = “dop”, k = 2
Output: 2 Replace b[2] with ‘g’, “dog” is a sub-string in “dogdog” which appears twice.

Approach: Make a list of all possible versions of the string b by iterating through all the lowercase letters and replacing the kth i.e. b[k] character in b with the current character. Then count the number of occurrences of the new string b in the original string a and store it in a variable count. After all the lowercase characters are used, print the count.

Below is the implementation of the above approach:

Python3

# Python3 implementation of the approach
import string
# Function to return the count of occurrences
def countOccurrence(a, b, k):   
    # Generate all possible substrings to
    # be searched
    x = []
    for i in range(26):
        x.append(b[0:k] + string.ascii_lowercase[i] + b[k + 1:])
    # Now search every substring 'a' and
    # increment count  
    count = 0
    for var in x:
        if var in a:
            count += a.count(var)
            
    return count
# Driver code
a, b = "feeds", "ee"
k = 1
print(countOccurrence(a, b, k))



Output:

2

Explore More

Python 10 Programs for Beginners

Program 1:Write a program to create a 2D array using NumPy. Output: Program 2: Write a program to convert a python list to a NumPy array. Output: Program 3: Write a program to create matrix of 3×3 from 11 to 30. Output: Program 4: Write a program to create a data frame to store data of candidates who appeared in

Find index of first occurrence when an unsorted array is sorted

Find index of first occurrence when an unsorted an array is sorted Given an unsorted an array and a number x, find an index of first occurrence of x when

Find sum non repeating distinct elements array

Find sum of non-repeating (distinct) elements in an array Given an integer an array with repeated elements, the task is to find the sum of all distinct elements in the