H
H
HelloDarknessMyOldFried2020-07-19 20:53:12
Python
HelloDarknessMyOldFried, 2020-07-19 20:53:12

IndexError: string index out of range - what is the reason?

Good day!
I'm a beginner, I'm trying to write a program that will find duplicate letters in a string, count their number in a row, output something like this: s = 'aaaabbсaa' is converted to 'a4b2с1a2'.
But at the output I get the error IndexError: string index out of range. The error occurs after using the for in loop.
Please help, I am attaching the code below.

genome = 'aaaabbcaa'
a = 1
s = 1
g = ''
for i in genome:
    if genome[a-1]==genome[a]:
        a += 1
        s += 1
    else:
        g += (genome[a-1]+str(s))
        a += 1
        s += 1
print(g)
----------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-176-241c9dc2be5a> in <module>
      4 g = ''
      5 for i in genome:
----> 6     if genome[a-1]==genome[a]:
      7         a += 1
      8         s += 1

IndexError: string index out of range

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2020-07-19
@HelloDarknessMyOldFried

HelloDarknessMyOldFried , I would suggest

following code

genome = 'aaaabbcaa'
cnt = 0
res = ''
for i in range(len(genome)):
  newSymb = i == 0 or genome[i] != genome[i - 1]
  if newSymb:
      if cnt > 0: g += str(cnt)
      res += genome[i]
      cnt = 1
  else:
      cnt += 1
res += str(cnt)

print(res)

H
Hcuy, 2020-07-19
@Hcuy

Alternatively, you can also consider my version:

spoiler
genome = 'aaaabbcaa'
gn = list(genome)
arr = []
text = ''
ln = len(gn)
for i in range(ln):
  a = 0
  for j in range(ln-1):
    if gn[i] == gn[j+1]:
      a +=1	
  text = gn[i] + str(a)
  arr.append(text)

arr = ''.join(arr)
print (arr)

The only thing left to do is remove the duplicate elements and do something with the last 'aa'. Good luck!

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question