Hi, I wrote a recursive function to find the no. of instances of a substring in the parent string. The way I am keeping count is by declaring/initialising count as a global variable outside the function's scope. Problem is, it'll give me correct results only the first time the function is run, because after that count != 0 to begin with. And if i have it inside the function, than each time it is called recursively, it'll be set to 0.
count=0
def countSubStringMatchRecursive(target,key):
index=find(target,key)
global count
targetstring=target
if index>=0:
count=count+1
target=target[index+len(key):]
countSubStringMatchRecursive(target,key)
else :
pass
return "No. of instances of", key, 'in', targetstring, 'is', count
Note: I am looking for the solution for a recursive
function specifically, I have an iterative function that does work fine.
EDIT: Thank You all, this was part of homework, so I was only using the string module