How to keep count in a recursive function?

后端 未结 11 802
甜味超标
甜味超标 2020-12-30 00:16

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

11条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-30 00:44

    Another way could be to have a third optional parameter on the countSubStringMatchRecursive function called count that is originally set to 0. That way you could keep track of the count. This would expose the count variable to the outside world which might not be desirable, but since it's no worse than your global variable I don't think it would be a problem in your case.

    You would also have to change the code to make the last recursive call be the call that gives the return statement to the outside world. See this example (untested):

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

    Edit: I realised that you would need a fourth parameter to be able to keep the original string traveling along the recursion. This is probably a less than optimal solution and I would recommend using Greg Hewgill's solution. It has a clean separation between the interactions with the outside and the "business logic", making the code more reusable!

提交回复
热议问题