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
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