python - compressing a string with repeating symbols -


i'm learning python , challenged exercise compress string. input goes 'aaaabbcccca' output has 'a4b2c4a1'. did it, have feeling solution rather clumsy. know, answer task. code is:

a = input() l = int(len(a)) c = int() b = str() = 0 while c <l:     if a[i] == a[c]:         c += 1     else:         b += (a[i] + str(c-i))         = c b += (a[i] + str(c-i)) print(b) 

here alternative one(ish) liner:

import itertools  = "aaaabbcccca" print "".join(["%s%u" % (g[0], len(g)) g in [list(g) k,g in itertools.groupby(a)]]) 

which prints:

a4b2c4a1 

to see how works, can split line components get:

groups = [list(g) k,g in itertools.groupby(a)] print groups  lengths = ["%s%u" % (g[0], len(g)) g in groups] print lengths  print "".join(lengths) 

this prints following:

[['a', 'a', 'a', 'a'], ['b', 'b'], ['c', 'c', 'c', 'c'], ['a']] ['a4', 'b2', 'c4', 'a1'] a4b2c4a1 

alternatively make use of k , g @ same time:

print "".join(["%s%u" % (k, len(list(g))) k,g in itertools.groupby(a)]) 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -