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?
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 sum
:
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
To avoid the nested sum
calls, you can use itertools.islice
:
from itertools import groupby, islice
g = groupby("aooooaooaoo")
res = sum(1 for _, j in g for _ in islice(j, 1, None)) # 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With