Reputation: 300
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??
Upvotes: 1
Views: 62
Reputation: 1491
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'
Upvotes: 1
Reputation: 17291
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
Upvotes: 1