How to keep count in a recursive function?

python, recursion

Solution

One way to modify your code would be to use a local function as follows:

def countSubStringMatchRecursive(target,key):
    def countit(target,key,count):
        index=find(target,key)
        if index>=0:
            target=target[index+len(key):]
            count += countit(target,key,count) + 1
        return count
    return "No. of instances of", key, 'in', target, 'is', countit(target,key,0)

Problem

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` 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

Original source

Related problems