Reputation: 35
I'm trying to figure out how I can count the number of letters in a string that occur 3 times. The string is 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)
Upvotes: 3
Views: 5252
Reputation: 39
We can count the chars in the string through 'for' loop
s="abbbaaaaaaccdaaab"
st=[]
count=0
for i in set(s):
print(i+str(s.count(i)),end='')
Output: a10c2b4d1
Upvotes: 1
Reputation: 414265
To count 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
Upvotes: 3
Reputation: 6317
To count the chars in the 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 as follows:
>>> result = [char for char in counter if counter[char] == 3]
>>> print(result)
['e', 'o']
If you want to match consecutive characters only, you can use regex (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']
This will also match if the same character appears three consecutive times multiple times (e.g. on "aaabcaaa"
, it will match 'a'
twice). Matches are non-overlapping, so on "aaaa"
it will only match once, but on "aaaaaa"
it will match twice. Should you not want multiple matches on consecutive strings, modify the regex to r"(.)\1\1(?!\1)"
. To avoid matching any chars that appear more than 3 consecutive times, use (.)(?<!(?=\1)..)\1{2}(?!\1)
. This works around a problem with Python's regex module that cannot handle (?<!\1)
.
Upvotes: 2