Count max substring of the same character

Viewed 169

i want to write a function in which it receives a string (s) and a single letter (s). the function needs to return the length of the longest substring of this letter. i dont know why the function i wrote doesn't work for exmaple: print(count_longest_repetition('eabbaaaacccaaddd', 'a') supposed to return '4'

    def count_longest_repetition(s, c):
        n= len(s)
        lst=[]
        length_charachter=0
        for i in range(n-1):
            if s[i]==c and s[i+1]==c:
                if s[i] in lst:
                    lst.append(s[i])
                    length_charachter= len(lst)
        return length_charachter
4 Answers

Due to the condition if s[i] in lst, nothing will be appended to 'lst' as originally 'lst' is empty and the if condition will never be satisfied. Also, to traverse through the entire string you need to use range(n) as it generates numbers from 0 to n-1. This should work -

def count_longest_repetition(s, c):
    n= len(s)
    length_charachter=0
    max_length = 0
    for i in range(n):
        if s[i] == c:
            length_charachter += 1
        else:
            length_charachter = 0
        max_length = max(max_length, length_charachter)

    return max_length

I might suggest using a regex approach here with re.findall:

def count_longest_repetition(s, c):
    matches = re.findall(r'' + c + '+', s)
    matches = sorted(matches, key=len, reverse=True)
    return len(matches[0])

cnt = count_longest_repetition('eabbaaaacccaaddd', 'a')
print(cnt)

This prints: 4

To better explain the above, given the inputs shown, the regex used is a+, that is, find groups of one or more a characters. The sorted list result from the call to re.findall is:

['aaaa', 'aa', 'a']

By sorting descending by string length, we push the longest match to the front of the list. Then, we return this length from the function.

This can also be done by groupby

from itertools import groupby
def count_longest_repetition(text,let):
    return max([len(list(group)) for key, group in groupby(list(text)) if key==let])



count_longest_repetition("eabbaaaacccaaddd",'a')

#returns 4

Your function doesn't work because if s[i] in lst: will initially return false and never gets to add anything to to the lst list (so it will remain false throughout the loop).

You should look into regular expressions for this kind of string processing/search:

import re
def count_longest_repetition(s, c):
    return max((0,*map(len,re.findall(f"{re.escape(c)}+",s))))

If you're not allowed to use libraries, you could compute repetitions without using a list by adding matches to a counter that you reset on every mismatch:

def count_longest_repetition(s, c):
    maxCount = count = 0
    for b in s:
        count = (count+1)*(b==c)
        maxCount = max(count,maxCount)
    return maxCount
Related