Overlapping Count Of Substring In A String In Python
I want to find all the counts (overlapping and non-overlapping) of a sub-string in a string. I found two answers one of which is using regex which is not my intention and the othe
Solution 1:
defsliding(a, n):
return (a[i:i+n] for i in xrange(len(a) - n + 1))
defsubstring_count(a, b):
returnsum(s == b for s in sliding(a, len(b)))
assertlist(sliding('abcde', 3)) == ['abc', 'bcd', 'cde']
assert substring_count('ababaa', 'aba') == 2
Solution 2:
Does this do the trick?
def count(string, substring):
n = len(substring)
cnt = 0for i in range(len(string) - n):
ifstring[i:i+n] == substring:
cnt += 1return cnt
print count('ababaa', 'aba') # 2
I don't know if there's a more efficient solution, but this should work.
Solution 3:
count = len(set([string.find('aba',x) for x in range(len(string)) ifstring.find('aba',x) >= 0]))
Solution 4:
Here, using re.finditer() is the best way to achieve what you want.
import re
defget_substring_count(s, sub_s):
returnsum(1for m in re.finditer('(?=%s)' % sub_s, s))
get_substring_count('ababaa', 'aba')
# 2 as response
Solution 5:
Here's a function you could use:
defcount(haystack, needle):
returnlen([x for x in [haystack[i:j+1] for i in xrange(len(haystack)) for j in xrange(i,len(haystack))] if x == needle])
Then:
>>>count("ababaa", "aba")
2
Post a Comment for "Overlapping Count Of Substring In A String In Python"