How can i get count of irregular repeating characters?

Question:

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??

Answers:

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
Answered By: Alexander

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


from itertools import groupby

s = 'aaabbbaaa'

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

print(compressed)
# '3a3b3a'
Answered By: Daniel Hao

what result do you expect to get if the string has single characters? suppose we should just skip a single character:

from re import sub

s = 'aabbbcaaabc'
sub(r'(w)1*',lambda m: f"{l if (l:=len(m[0]))>1 else ''}{m[1]}",s)

>>>
# '2a3bc3abc'
Answered By: SergFSM
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.