addicted_programmer
addicted_programmer

Reputation: 47

count the highest consecutive occurrence of a string in Python

How can I find the maximum number of occurrences of a string in python? for example if string s is :

s="**hellohellohello**applefruitcat**hellohello**lionlizard**hellohellohellohello**"

and I'm looking for the max number of consecutive "hello" this should return 4 since the max number of consecutive occurrence of hello is 4

I came up with a code to test the find function and surprisingly it gives me 4 which is the maximum number of consecutive occurrence I also tried different strings and it gave me the correct maximum. What I don't understand here is how is it returning the max number of occurrences, if no max function is used? I thought it would return how many times hello was found.

this is the code:

for i in range(len(s)):
if s.find('hello' * i) != -1:
    x = i

Upvotes: 0

Views: 467

Answers (2)

John Deo
John Deo

Reputation: 81

The code loops over the length of the string trying to find 'hello' then 'hellohello' and so on. It will set x to the current value of i if it found that many repetitions.

It will still search for 'hello'*5 and 'hello'*6 in your case but won't find it in the string thus leaving x to the last value of i it could actually find.

A slightly better version would be:

for i in range(len(s)/len('hello')):
  if s.find('hello' * i) != -1:
    x = i

Upvotes: 0

Mureinik
Mureinik

Reputation: 311373

This snippet loops over consecutive concatenated "hello"s. It first checks if there's a "hello" in the string, then "hellohello", etc, until it fails. The longest sequence that was there is the max number of consecutive "hello"s.

Upvotes: 1

Related Questions