this question has answer here:
- string count overlapping occurrences 17 answers
just started learning python. had create function count sub-string within string. decided use count() function of string module doesn't hoping for.
it seems count() function iterate through string , if find sub-string, move add count continue it's iteration @ end of sub-string.
below code , test running:
def count(substr,thestr): counter = 0 counter = thestr.count(substr, 0, len(thestr)) return counter print(count('is', 'mississippi')) # expected count: 2 pass print(count('an', 'banana')) # expected count: 2 pass print(count('ana', 'banana')) # expected count: 2 test failed: count: 1 print(count('nana', 'banana')) # expected count: 1 pass print(count('nanan', 'banana')) # expected count: 0 pass print(count('aaa', 'aaaaaa')) # expected count: 5 test failed: count: 2
try taking individual sub strings of length of desired string, , checking them:
def count(sub, whole): total = 0 in range(0, len(whole)-len(sub)+1): if sub == whole[i:i+len(sub)]: total+=1 return total
>>> print(count('is', 'mississippi')) 2 >>> # expected count: 2 pass ... >>> print(count('an', 'banana')) 2 >>> # expected count: 2 pass ... >>> print(count('ana', 'banana')) 2 >>> # expected count: 2 pass ... >>> print(count('nana', 'banana')) 1 >>> # expected count: 1 pass ... >>> print(count('nanan', 'banana')) 0 >>> # expected count: 0 pass ... >>> print(count('aaa', 'aaaaaa')) 4 >>> # expected count: 4 pass ...
Comments
Post a Comment