How to keep count in a recursive function?

后端 未结 11 783
甜味超标
甜味超标 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:54

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

提交回复
热议问题