How to keep count in a recursive function?

后端 未结 11 799
甜味超标
甜味超标 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 01:09

    I'm doing this course on OpenCourseware, it's great. Anyways, this is what I did. I took inspiration from adamse above.

    def countSubStringMatchRecursive(target, key, counter = 0):
        if find(target,key) == 0:
            countSubStringMatchRecursive(target[1:], key, counter + 1)
        elif find(target,key) > 0:
            countSubStringMatchRecursive(target[1:], key, counter)
        elif find(target,key) == -1:
            print counter
    

提交回复
热议问题