Help me understand what exactly is wrong in my code? Task: write a genomic code compression algorithm. Example: Input: AACAA Output: A2C1A2

genome = input() a = 0 b = 1 result = "" c = 1 one = "1" for i in genome: if b > len(genome) - 1: break if genome[a] == genome[b]: c += 1 elif c >= 2: c = str(c) result = genome[a] + c c = int(c) c = 1 else: result = genome[a] + one a += 1 b += 1 print(result) 

Reported as a duplicate by participants nick_n_a , Sergey Gornostaev , gil9red , Peter Samokhin , MaxU python 11 Jul '18 at 7:14 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

The first thing that catches your eye is the variable "i" in the loop, which is not used. And in general, you have extra movements.

 genome = input() a = 0 # счетчик текущего символа b = genome[0] # первый символ входных данных result = "" for i in genome: if i == b: # сравниваем, если одинаковые, увеличиваем счетчик a += 1 else: result += b + str(a) # иначе, сохраняем в результат # символ и его количество a = 1 # сбрасываем счетчик b = i # задаем переменной новый символ, сменивший старый result += b + str(a) # сохраняем данные по последнему символу print(result) # выводим результат 

You can still add the string result += b + str(a) to a separate function, but in this code it does not make sense.