Reputation: 41
I am working on a python problem which has a string such as “aaabbcc” and a number n (integer). I have to display a sequence of any Alphabetic character that appears exactly n times.
I have tried the code
import collections
str1 = 'aaabbcc'
d = collections.defaultdict(int)
for c in str1:
d[c] += 1
for c in sorted(d, key=d.get, reverse=True):
if d[c] > 1:
print(c, d[c])
But I am getting output as
a 3
b 2
c 2
I am expecting output as the integer input 3
is input is taken, from user.
integer= 3
sequence= aaa
Is there any alternative solution?
Upvotes: 2
Views: 52
Reputation: 521279
Here is a regex based approach which seems to work:
input = "ddaaabbbbbbbbccceeeeeee"
n = 3
for match in re.finditer(r'(.)(?!\1)(.)\2{' + str(n-1) + r'}(?!\2)', input):
print(match.group(0)[1:])
aaa
ccc
The regex pattern being used in the exact example above is this:
(.)(?!\1)(.)\2{2}(?!\2)
This says to:
(.) match and capture any single character
(?!\1) assert that the next character is different
(.) then match and capture that next character
\2{2} which is then followed by that same character exactly twice (total of 3)
(?!\2) after three instances, the character that follows is NOT the same
Upvotes: 1
Reputation: 46859
a loop-based approach (that should be pretty straight-forward):
str1 = 'aaabbcc'
n = 3
count = 1
last = None
for char in str1:
if last == char:
count += 1
else:
if count == n:
print(f'integer: {n} sequence: {n*last}')
last = char
count = 1
if count == n:
print(f'integer: {n} sequence: {n*last}')
the last if statement is there to print a solution if one was found including the last character of str1
.
Upvotes: 0
Reputation: 46859
an itertools.groupby
-based approach:
from itertools import groupby
str1 = 'aaabbcc'
n = 3
for key, group in groupby(str1):
if len(tuple(group)) == n:
print(f'integer: {n} sequence: {n*key}')
withot a key
groupby
will group the sequence by identity - i.e. every time the letter in str1
changes it will yield that letter and its occurrences.
Upvotes: 1