Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i get count of irregular repeating characters?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading