I'm going through Cracking the Code and there is this question where they ask to write a method for string compression so:
aabbccccaa
Would become:
a2b1c4a2
I came up with this:
''.join(y+str.count(y) for y in set(str))
But my output was:
a5c4b1
Could someone point me in the clean direction?
Sorry for bad edits, I'm on a cellphone
You could use groupby to do the work for you:
>>> from itertools import groupby
>>> s = 'aabbccccaa'
>>> ''.join(k + str(sum(1 for x in g)) for k, g in groupby(s))
'a2b2c4a2'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With