I wrote a recursive function to find the number of instances of a substring in the parent string.
The way I am keeping count is by declaring/initialising count
Your recursive function has O(n^2) performance because it copies the remaining contents of the string each time it finds a match. This is slower than the iterative solution O(n) and unnecessarily so.
You can easily rewrite it to be faster, and at the same time simplify the code and extend its functionality by passing a start index for the search as an optional parameter to the function:
def countSubStringMatchRecursive(target, key, start_index = 0):
index = target.find(key, start_index)
if index >= 0:
return countSubStringMatchRecursive(target, key, index + len(key)) + 1
return 0
target_string = 'an apple and a banana'
key = 'an'
count = countSubStringMatchRecursive(target_string, key)
print "Number of instances of %r in %r is %d" % (key, target_string, count)
Output:
Number of instances of 'an' in 'an apple and a banana' is 4
Update: If you really want to use the string module's find function, you can do this just by changing one line:
index = find(target, key, start_index)