How to keep count in a recursive function?

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

    Not untested ...

    code:

    def countSubStringMatchRecursive(target, key, count=0):
        #### index = find(target, key) # HUH?
        index = target.find(key)
        if index >= 0:
            count += 1
            target = target[index+len(key):]
            count = countSubStringMatchRecursive(target, key, count)
        return count
    
    for test in ['', 'bar', 'foo', 'foofoo', 'foo foo foo fo']:
       print countSubStringMatchRecursive(test, 'foo'), test.count(key), repr(test)
    

    output:

    0 0 ''
    0 0 'bar'
    1 1 'foo'
    2 2 'foofoo'
    3 3 'foo foo foo fo'
    

    I'm presuming that this is just amusement or homework ... recursive function must be slower than corresponding Python iterative solution, which will be naturally slower than using target.count(key) ... so I haven't bothered with fixing all the problems your version had ... but do read PEP-008 :-)

    Comments on string module

    You commented that you had omitted from string import find. What version of Python are you using? What is the last update date on the book or tutorial that you are using?

    From the start of the string module (it will be on your computer as /Lib/string.py; I'm quoting from the 2.6 version):

    """A collection of string operations (most are no longer used).

    Warning: most of the code you see here isn't normally used nowadays. Beginning with Python 1.6, many of these functions are implemented as methods on the standard string object. They used to be implemented by a built-in module called strop, but strop is now obsolete itself.

    etc """

    and here is that file's code for the find function (stripped of comments):

    def find(s, *args):
        return s.find(*args)
    

    so using string.find(target, key) instead of target.find(key) is a waste.

提交回复
热议问题