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
steps = 0
def addPersistence(number, steps):
steps += 1
if len(str(number))==1:
print(str(number) + "\nDone---------------------------------------------------")
print("TOTAL STEPS " + str(steps-1))
digits = [int(i) for i in str(number)]
result = 0
for j in digits:
result += j
if len(str(number)) != 1:
print(number)
addPersistence(result, steps)
This is a example copied from one of my projects. This function is to determine to addition persistence of a number (which is adding the digits of a number and repeating it until the number gets to 1) but it surely can be reusable and you can use your function like this (This is Python 3 code, if you want to change it to Python 2, it will still work):
count=0
def countSubStringMatchRecursive(target,key,count):
index=find(target,key)
targetstring=target
if index>=0:
count+=1
target=target[index+len(key):]
countSubStringMatchRecursive(target,key,count)
else :
pass
print("STEPS: "+str(count))
You might notice my code and that code are a little bit different. Why? The answer is that the number of steps it takes for a number to get to 1 using that function is that the last call isn't included in my function because it's a duplication of the call before that.