How to count consecutive repetitions of a substring in a string?

Viewed 8580

I need to find consecutive (non-overlapping) repetitions of a substring in a string. I can count them but not consecutive. For instance:

string = "AASDASDDAAAAAAAAERQREQREQRAAAAREWQRWERAAA"
substring = "AA"

here, "AA" is repeated one time at the beginning of the string, then 4 times, then 2 times, etc. I should select the biggest one, in this example - 4 times.

How can I do that?

4 Answers

Regular expressions shine when searching through strings. Here you can find all groups of one or more AA with (?:AA)+ the (?: simply tells the engine to interpret the parentheses for grouping only.

Once you have the groups you can use max() to find the longest based on length (len()).

import re

s = "AASDASDDAAAAAAAAERQREQREQRAAAAREWQRWERAAA"

groups = re.findall(r'(?:AA)+', s)
print(groups)
# ['AA', 'AAAAAAAA', 'AAAA', 'AA']

largest = max(groups, key=len)
print(len(largest) // 2)
# 4

one way to do it with basic operations is to search for the pattern "AA" in the string and add "AA" to the search until you don't find any more:

string  = "AASDASDDAAAAAAAAERQREQREQRAAAAREWQRWERAAA"
count   = 0
pattern = "AA"
while pattern in string:
    count += 1
    pattern += "AA"

output:

print(count) # 4

It could also be written on a single line like this:

count = next(r-1 for r in range(1,len(string)+1) if "AA"*r not in string)

You could also use the find() method instead of the in operator which would allow the search to continue from the first match instead of starting over from the beginning of the string:

string  = "AASDASDDAAAAAAAAERQREQREQRAAAAREWQRWERAAA"
pattern = "AA"

repeated = ""
position = 0
while position >= 0:
    repeated += pattern
    position = string.find(repeated,position)
count = len(repeated)//len(pattern)-1  
        
print(count) # 4

Try this. This simply iterates through the words and updates the max on each iteration.

string = "AASDASDDAAAAAAAAAERQREQREQRAAAAREWQRWERAAA" #normal case
#string_2 = "BAASDAAAAAAAAERQREQREQRAAAAREWQRWERAAA" #edge case

substring = "AA"
max_count=0
count = 0
for i in range(0,len(string),len(substring)):
    print(string[i-len(substring):i])
    if string[i-1:i] == substring[:1] and count == 0:
        i = i+(len(substring)-1)
    if string[i-len(substring):i] == substring:
        count+= 1
    else:
        count = 0
    max_count = max(max_count,count)

print(max_count)

outputs

4

Since you are new, try using a visualizer to get a better understanding of the code execution.

string = "AASDASDDAAAAAAAAERQREQREQRAAAAREWQRWERAAA"
substring = "AA"
count = 0
string_length = len(string)
substring_length = len(substring)
for i in range( round( string_length / substring_length ) ):
    if (i * substring) in string:
        count = i
return count
Related