PYTHON - Fibonacci Sequence Implementation

Asked

Viewed 92 times

-2

I’m trying to put the Fibonacci sequence in Python in Vscode, and every time I try to run the following code, the error appears:

line 8, in <module>
    Fibonacci[i] = proximo
IndexError: list assignment index out of range

Someone can give me a light on how to fix ?

Fibonacci = [0]*100
anterior = 0
proximo = 1
i = 0


while (i <= 100):
    Fibonacci[i] = proximo
    proximo = proximo + anterior
    anterior = proximo - anterior
    i = i + 1


print(Fibonacci)
  • 1

    Fibonacci.append(proximo)

  • Remember that in Python lists are dynamic and can increase/decrease size as needed, so you do not need to create the list with 100 artificial values at the beginning, just do so: https://ideone.com/ARLpBG

1 answer

1

You’re making a classic mistake of off-by-one (error-of-one).

while (i <= 100): will make you access up to the value Fibonacci[100], which does not exist - values for the list have been initialized at positions from 0 to 99.

Just switch to while (i < 100): and your code should run.

Browser other questions tagged

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