s = 'aaaabbcaa' is converted to 'a4b2c1a2', that is, groups of identical characters of the original string are replaced with this symbol and the number of its repetitions in this position of the string.

Write a program that reads a string, encodes it with the proposed algorithm, and outputs the encoded sequence to standard output. Encoding must be case sensitive

This is what I did, but it doesn’t work and I can’t understand why:

str1 = input() str2 = "" index = 0 tmp = len(str2) for i in range(len(str1)): tmp = len(str2) if i ==0 and len(str1) == 1: index +=1 print(str1[i] + str(index)) break elif i ==0: str2 = str2 + str1[i] index +=1 elif i >0 : if tmp ==0 : str2 = str2 + str1[i] index == 1 #tmp ==1 elif str2[tmp-1] == str1[i] and tmp ==1: index +=1 elif tmp >1 : index +=1 print(str2[tmp-1]) elif str2[tmp] == str1[i] and str2[tmp -1] == str1[i]: index +=1 else: str2=str2 + str1[i] + str(index); index==0; tmp=len(str2) print(str2) 

    2 answers 2

     from itertools import groupby s = input() print(''.join('{}{}'.format(k, sum(1 for _ in g)) for k, g in groupby(s))) 
    • sum(1 for _ in g) can be replaced by len(list(g)) - gil9red

    No import

     s = 'aaaabbсaa' r = '' for c in s: if not len(r): r = c + '1' else: if c == r[-2]: r = '{}{}'.format(r[:-1], int(r[-1]) + 1) else: r = '{}{}{}'.format(r, c, '1') print(r) a4b2с1a2