Python Practice › String Programs › Program 8
Longest run of a repeated character
Write a Python program to find the character that repeats most times in a row (consecutively) in a string.
Input
"aabbbbcccdd"
Output
b 4
Approach
- Walk through the string, counting the current run, and remember the longest one.
Solution
text = "aabbbbcccdd"best_char, best_len = text[0], 1run_len = 1for i in range(1, len(text)): if text[i] == text[i - 1]: run_len += 1 else: run_len = 1 if run_len > best_len: best_char, best_len = text[i], run_lenprint(best_char, best_len)Output
b 4
Line by line
Lines 5-8
The run grows while characters repeat and resets on a change.
Lines 9-10
Save the run if it is the longest so far.
Tip
itertools.groupby(text) groups consecutive equal characters for you.
Learn the concept
New to this topic? Read the lesson, then come back.