Home > OS >  How can i get count of irregular repeating characters?
How can i get count of irregular repeating characters?

Time:12-10

Input is xyz = 'aaabbbaaa', I want output as 3a3b3a

xyz = 'aaabbbaaa'
p = xyz[0]
i = 0
out = {}
while i < len(xyz):
    if p == xyz[i]:
        if xyz[i] not in out:
            out[xyz[i]] = []
        out[xyz[i]].append(xyz[i])
    else:
        p = xyz[i]
    i  = 1
print(out)

Help me, How can i achieve this??

CodePudding user response:

This is likely the simplest method and easiest to understand.

Create a tally variable and increment it when you see repeating characters, then when you see a non repeating character write the previous character and the tally to a string and start the tally back to 1.... repeat until string ends

xyz = 'aaabbbaaa'
tally = 1
string = ''
prev = xyz[0]
for char in xyz[1:]:
    if char == prev:
        tally  = 1
    else:
        string  = str(tally)   prev
        prev = char
        tally = 1
string  = str(tally)   prev
print(string)   # 3a3b3a

CodePudding user response:

Alternatively, if you want to try to explore itertools module groupby this can be simpler:


from itertools import groupby

s = 'aaabbbccc'

compressed = ''.join((str(len(list(group))) char) for char, group in groupby(s))

print(compressed)
# '3a3b3c'

# Or try the collection module Counter()
from collections import Counter

counts = Counter(s)
counts
Counter({'a': 3, 'b': 3, 'c': 3})

compressed = ''.join(str(v) k for k, v in counts.items())
print(compressed)
# '3a3b3c'
  • Related