Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String compression using repeated chars count

Tags:

python

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

like image 418
Onilol Avatar asked Sep 18 '26 11:09

Onilol


1 Answers

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'
like image 101
niemmi Avatar answered Sep 20 '26 00:09

niemmi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!