Counting instances of consecutive repeating letters in a Python string

I am trying to figure out how I can count the number of letters in a string that happens 3 times. String from raw_input()

.

For example, if my input is:

abceeedtyooo 

      

The output should be: 2

This is my current code:

print 'Enter String:'
x = str(raw_input (""))

print  x.count(x[0]*3)

      

+3


source to share


2 answers


To count the characters in a string, you can use collections.Counter

:

>>> from collections import Counter
>>> counter = Counter("abceeedtyooo")
>>> print(counter)
Counter({'e': 3, 'o': 3, 'a': 1, 'd': 1, 'y': 1, 'c': 1, 'b': 1, 't': 1})

      

Then you can filter the result like this:

>>> result = [char for char in counter if counter[char] == 3]
>>> print(result)
['e', 'o']

      



If you only want to match sequential characters, you can use a regular expression (cf. re

):

>>> import re
>>> result = re.findall(r"(.)\1\1", "abceeedtyooo")
>>> print(result)
['e', 'o']
>>> result = re.findall(r"(.)\1\1", "abcaaa")
>>> print(result)
['a']

      

It will also match if the same character appears three times in a row multiple times (for example, on "aaabcaaa"

, it will match 'a'

twice). Matches do not overlap, so "aaaa"

it will only match once, but "aaaaaa"

it will match twice. If you don't need multiple matches on consecutive lines, change the regex to r"(.)\1\1(?!\1)"

. To avoid matching any characters that appear more than three times in a row, use(.)(?<!(?=\1)..)\1{2}(?!\1)

. This is due to an issue with the Python regex module that it cannot handle (?<!\1)

.

+2


source


To count the number of consecutive duplicate letters that occur exactly 3 times:



>>> from itertools import groupby
>>> sum(len(list(dups)) == 3 for _, dups in groupby("abceeedtyooo"))
2

      

+2


source







All Articles