How to keep count in a recursive function?

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

    Taking into account overlapping occurrences and maintaining the original definition from MIT this is the simpler and more compact code that I can get.

    code:

    from string import *
    def countSubStringMatchRecursive(target, key):
        index = find(target, key)
        if index > -1:
            return countSubStringMatchRecursive(target[index + 1:], key) + 1
        return 0
    
    
    def test(target, key):
        instances = countSubStringMatchRecursive(target, key)
        if instances == 0:
            print "No instance of %r in %r" % (key, target)
        else:
            print "Number of instances of %r in %r: %d" % (key, target, instances)
    
    test("atgacatgcacaagtatgcat","ggcc")
    test("atgacatgcacaagtatgcat","atgc")
    test("banana", "ana")
    

    output:

    No instance of 'ggcc' in 'atgacatgcacaagtatgcat'

    Number of instances of 'atgc' in 'atgacatgcacaagtatgcat': 2

    Number of instances of 'ana' in 'banana': 2

提交回复
热议问题