I am trying to write a code which replaces repeating symbols in a string with a symbol and number of its repeats (like that: "aaaaggggtt" --> "a4g4t2"). But I'm getting string index out of range error((
seq = input()
i = 0
j = 1
v = 1
while j<=len(seq)-1:
if seq[i] == seq[j]:
v += 1
i += 1
j += 1
elif seq[i] != seq[j]:
seq.replace(seq[i-v:j], seq[i] + str(v))
v = 1
i += 1
j += 1
print(seq)
line 6, in if seq[i] == seq[j]: IndexError: string index out of range
UPD: After changing len(seq) to len(seq)-1 there is no more string index error, but the code still doesn't work.
Input: aaaaggggtt
Output:aaaaggggtt (same)
Using Counter, you get a dictionary with the caracters as key and the number of repetition of that caracter as value. Then I iterated the dictionary, creating a list in witch each element was made by key + number of that character. I joined the list obtaining the string you were looking for.
OUTPUT:
a4g4t2
You can iterate over the string, keeping a running counter and create your string as you go
Or you can approach this using itertools.groupby
The output will be
simple way: