Counting all permutations of a substring
Azolex
cretin at des.alpes.ch
Wed Apr 5 20:01:09 EDT 2006
[counting all (possibly overlapping) occurences of a substring in a string]
def count_subs(s,subs,pos=0) :
pos = 1+s.find(subs,pos)
return pos and 1+count_subs(s,subs,pos)
or equivalently
def count_subs(s,subs)
pos,cnt = 0,0
while True :
pos = 1+s.find(subs,pos)
if not pos :
return cnt
cnt += 1
or even (using the helper functions of my last post in the "small
challenge" thread)
def count_subs(s,subs) :
cnt = 0
for pos1 in echoback(1+s.find(subs,pos) for pos in itially(0)) :
if not pos1 :
return cnt
cnt += 1
(I've minimally tested only the first version)
More information about the Python-list
mailing list