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
Here's something similar to Greg Hewgill's answer. However, instead we pass along the current count each time we call the function, and then return the count when there are no more matches to be made. While I suspect it makes no difference in Python, in languages that implement tail-call recursion, this allows each successive call to do_count
to be optimised away on the call stack. This means that each call to do_count
doesn't cause the call stack to grow.
def count_sub_strings(target, key):
def do_count(target, key, count):
index = target.find(key)
if index >= 0:
target = target[index + len(key):]
return do_count(target, key, count + 1)
else:
return count
return "No. of instances of %s in %s is %s" % (key, target, do_count(target, key, 0))