Hints
I would follow this steps:
- Create a list where I will store my partial strings
- Start iterating the string
- Store the initial position and the current character
- Keep iterating until the character is different
- Store in the list the partial string from the initial position you stored until 1 less than the current position
- Update the initial position to the current one and the current character
- Use the list to create a
collections.Counter
About your code, the_string[i] == the_string[i]
will always be true.
SPOILER: solution
from collections import Counter
def repeating_letters(the_string):
partials = []
initial = 0
for i, character in enumerate(the_string):
if character == the_string[initial]:
continue
partials.append(the_string[initial:i])
initial = i
partials.append(the_string[initial:]) # Needed for the last partial string
return Counter(partials)
As @prahantrana mentions in a comment, getting the partials can be done in a one-liner with the groupby
method from the itertools
library.
from collections import Counter
from itertools import groupby
def repeating_letters(the_string):
return Counter(''.join(group) for _, group in groupby(the_string))
Or
from collections import Counter
from itertools import groupby
def repeating_letters(the_string):
return Counter(char*len(list(group)) for char, group in groupby(the_string))
I’m not sure which of them is faster.
3
solved To find number of continuous Repeating characters