How to keep count in a recursive function?

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

    Just a side note: all solutions presented (from the original Q to all the As) are solving a problem that's different than the specifically stated one (I imagine that's a bug in the specific problem statement, but, worth fixing if so;-). Consider:

    >>> 'banana'.count('ana')
    1
    >>> sum('banana'[x:x+3]=='ana' for x in range(len('banana')))
    2
    

    the first expression is counting the non-overlapping occurrences of 'ana' in 'banana'; the second one is counting all occurrences -- there are two occurrences in all, at indices 1 and 3 in 'banana', and they overlap. So given the problem statement, and I quote:

    find the no. of instances of a substring in the parent string.

    without any mention of "non-overlapping", it seems that overlapping occurrences should be counted. Of course, that's easy to fix, once noticed -- you just have to advance by 1 each time, instead of advancing by len(key) which leads you to skip overlapping occurrences.

    So, for example:

    import string
    
    def countit(target, key, startfrom=0):
        where = string.find(target, key, startfrom)
        if where < 0: return 0
        return 1 + countit(target, key, where+1)
    
    print countit('banana', 'ana')
    

    prints 2, counting both (overlapping) occurrences.

提交回复
热议问题