Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way to get the number of repeating character in a word?

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?

like image 314
emremrah Avatar asked Nov 08 '18 11:11

emremrah


1 Answers

Original question: 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

New question: 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
like image 56
jpp Avatar answered Oct 10 '22 00:10

jpp