Repeat loop with problem

Asked

Viewed 121 times

2

I have the algorithm below, and on the line while lista[i]==lista[i-1]: is returning the error:

index out of range

import random
n1=0
n2=0
n1=int(input('Insira um numero para inicio'))
n2=int(input('Insira um numero para limite'))
i=1
lista=[]
for i in [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]:
    lista.append(random.randint(n1,n2))
i=1
count=0
print(lista[i-1])
lista.sort()
while i<=15:
    while lista[i]==lista[i-1]: 
        lista.pop(i)
        lista.insert(i,random.randint(n1,n2))
    i+=1
print(lista)
  • Usually when you start a loop, the increasing variable always starts at 0, in the snippet lista[i-1] you’re making 0 - 1, so the result is -1 then he can’t find the index array, what you intend to do in this code?

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site (when you have enough score).

2 answers

4

The mistake is in while i<=15 that should be while i < 15. The list of 15 elements goes from 0 to 14, so you have to stop before you get to 15, you’re going up to 15 with the operator of "less or equal", can’t be equal, so when you get to it takes an element that doesn’t exist, the 15, and gives the error.

This code has some problems that don’t stop the execution, and it even seems to do some nonsense. And it could be more idiomatic in Python, but maybe if you take away everything that doesn’t make sense and isn’t the case.

  • That point here is also relevant to the problem!

2

Maniero’s answer is the most correct one. Just switch to while i < 15: that will no longer have this mistake.

I find it interesting that you put a condition so that n1 is less than N2, because if n1 == N2, your code will not give any error, but will enter an infinite loop, since randint will always return the same number.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.