I am trying to generate the Fibonacci value of a number efficiently, but my code returns this error:
"Traceback (most recent call last):
File "fibonacci_number.py", line 22, in <module>
print(fibonacci_number(input_n))
File "fibonacci_number.py", line 16, in fibonacci_number
next_num = fib_list[n-2] + fib_list[n-1]
IndexError: list index out of range"
Here is the full code:
def fibonacci_number(n):
assert 0 <= n <= 45
fib_list = [0, 1]
for i in range(2, n):
next_num = fib_list[n-2] + fib_list[n-1]
fib_list.append(next_num)
return fib_list[n]
if __name__ == '__main__':
input_n = int(input())
print(fibonacci_number(input_n))
I don't want to call fibonacci_number() recursively, as it will make me recalculate fib_list[n-2] and fib_list[n-1] over and over, which takes up time.
I found other people with similar issues, but using ".append()" seemed to resolve their issue of adding something new to a Python list.
Some things I've tried:
- fib_list = fib_list.append(next_num)
- fib_list.append(fib_list[n-2] + fib_list[n-1])
- declaring next_num separately and setting it equal to 0 before later updating its value