Reputation: 1783
I am trying to count how many time a sequence appears in a given string.
def count_seqence(str, seq):
count = 0
if seq in str:
count += 1
return count
print(count_seqence("the quick brown fox jumps over the lazy dog","he"))
But this only runs once and does not loop, how can i loop and count how many times appears, because i know looping would be for each char and not a seq, this is making me confusing.
Upvotes: 3
Views: 7328
Reputation: 1
Use count on your string, it will return the number of time it found your parameter value seq
def count_seqence(str, seq): return str.count(seq)
print count_seqence("kjdsflsdnf
Upvotes: 0
Reputation: 476750
Well since you use an if
, and not in a loop, that means that either the condition is True
, and thus you increment count
, or it is False
in which case you do not execute the body.
If you want to count numbers, you will need some "looping" mechanism. This does not have to be explicit, for example in
hides a loop as well. But this only results in True
or False
.
count_seqence('aaaa', 'aa')
is 2
)For non-overlapping counts, we can use str.count
:
def count_seqence(text, seq):
return text.count(seq)
in which case defining a specific function of course is rather useless. Note that the above will only count non-overlapping matches. For example when you count 'aa'
in 'aaaa'
you will get 2
, not 3
.
count_seqence('aaaa', 'aa')
is 3
)For overlapping, we will need to perform a str.find
, and update the "search window" until we no longer find a match, like:
def count_seqence(text, seq):
cnt = 0
idx = text.find(seq)
while idx >= 0:
cnt += 1
idx = text.find(seq, idx+1)
return cnt
We thus have an idx
that stores the index where the new match occurs, and each time that idx
is larger or equal to 0
(we found a match), we increment cnt
, and change idx
to the next match.
Upvotes: 6
Reputation: 124
Use string.count
method. Check Python documentation for that.
Example:
x = "wip wip I'm a sheep wip"
print(x.count("wip"))
Upvotes: 2
Reputation: 4379
Use count
on your string, it will return the number of time it found your parameter value seq
def count_seqence(str, seq):
return str.count(seq)
print count_seqence("kjdsflsdnf lskmfldsknffsdlkfnsldkmf", "ds")
Output
2
Upvotes: 4