I'm trying to get how many any character repeats in a word. The repetitions must be sequential.
For example, the method with input "loooooveee" should return 6 (4 times 'o', 2 times 'e').
I'm trying to implement string level functions and I can do it this way but, is there an easy way to do this? Regex, or some other sort of things?
So far I tried this:
def measure_normalized_emphasis(text): char = text[-1] emphasis_size = 0 for i in range(1, len(text)): if text[-i] == char: emphasis_size += 1 else: char = text[i - 1] return emphasis_size
And it returns 8 with "loooooveee".
order of repetition does not matter
You can subtract the number of unique letters by the number of total letters.
set applied to a string will return a unique collection of letters.
x = "loooooveee" res = len(x) - len(set(x)) # 6
Or you can use
collections.Counter, subtract 1 from each value, then
from collections import Counter c = Counter("loooooveee") res = sum(i-1 for i in c.values()) # 6
repetitions must be sequential
You can use
itertools.groupby to group sequential identical characters:
from itertools import groupby g = groupby("aooooaooaoo") res = sum(sum(1 for _ in j) - 1 for i, j in g) # 5