0

In input we getting string like

asdfssgAAatG

and output must be a compressed string with letter count. For example input

aabggtttf

must give

a2b1g2t3f1

so letter and how many times it repeated in row in output. The input

abc

must give

a1b1c1

in output. So i wrote some code for it:

a=str(input())+' '
count=1
b=1
r=''
for i in range (a.count('')-2):
  if a[i]==a[i+1]:
        b+=1
  else:
        count=b
        b=1
        r=r+a[i]+str(count)
if a!=' ':
    print(result=r[0:-1]+str(count))

For me code works flawless and when i put test input it give correct answer. But on site where i need to insert that code 'steptic.org' some of automated tests give error, and i cant complete this task. So here the question: what wrong with this code and what input can give error here? Maybe is here some simplier way to perform this task on Python? P.S Sry for my bad english =) P.S Capitalization matter, test content i cant see, i tryed some test data - all worked.. , seems i just cant think out data what gives incorrect answer.

Biggreen
  • 11
  • 3

2 Answers2

2

It's unclear what tests are failing and in what ways, so I can't comment on that.

However, you could use itertools.groupby() to achieve the desired results:

In [13]: s = 'aabggtttf'

In [14]: ''.join(('%s%d' % (l, sum(1 for _ in g))) for l, g in itertools.groupby(s))
Out[14]: 'a2b1g2t3f1'

Here:

  • for l, g in itertools.groupby(s) iterates over runs of identical letters;
  • '%s%d' % (l, sum(1 for _ in g))) produces a string consisting of the letter and the length of the run.
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • What's with the underscore in `sum(1 for _ in g)`? Thanks, @NPE – trinaldi Nov 25 '14 at 11:25
  • 1
    @Tico: It's just a variable like any other. It needs to have a name, but that name is not used. Following a common convention, I name the variable `_`. See http://stackoverflow.com/questions/5893163/underscore-in-python – NPE Nov 25 '14 at 11:27
0

if you are not worry about case of letter: using collections.Counter

>>> from collections import Counter
>>> my_string = 'asdfssgAAatG'
>>> "".join(sorted([x+str(y) for x,y in Counter(my_string).items()],key=lambda x:my_string.index(x[0])))
'a2s3d1f1g1A2t1G1'

create a function and return it:

>>> def count_it(my_string):
...     return "".join(sorted([x+str(y) for x,y in Counter(my_string).items()],key=lambda x:my_string.index(x[0])))
... 
>>> count_it('aabggtttf')
'a2b1g2t3f1'
>>> count_it('abc')
'a1b1c1'

using itertools.groupby:

>>> "".join([ x+str(len(list(y))) for x,y in itertools.groupby('aabggtttf')])
'a2b1g2t3f1'
Hackaholic
  • 19,069
  • 5
  • 54
  • 72