0

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
1
  • When i is varing,it finds ("hello"*i)....as an example,if i=3,it finds "hellohellohello" from the string.If it found, s.find('hello' * i) return the position of it(>0).... Commented Dec 1, 2020 at 9:09

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

so basically this part : ('hello' * i) != -1 keeps checking until it finds the longest sequences and returns it? I was confused because I thought it would count all the "hellos" in the string
Note the * i - in each iteration it looks for hello concatenated i times, until it can't find one (and -1 is returned).
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.