How to keep count in a recursive function?

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

    How about this?

    def count_it(target, key):
        index = target.find(key)
        if index >= 0:
            return 1 + count_it(target[index+len(key):], key)
        else:
            return 0
    
    
    print count_it("aaa bbb aaa ccc aaa", "aaa")
    

    Output:

    3
    

提交回复
热议问题