JavaScript
x
15
15
1
def fibonaci(i,memo):
2
if i == 0 or i == 1:
3
return i
4
5
if memo[i]==-1:
6
memo[i] = fibonaci(i-1,memo) + fibonaci(i-2,memo)
7
8
return memo[i]
9
10
def fibo(n):
11
a = []
12
return fibonaci(n,a)
13
14
print(fibo(2))
15
I’m a Java programmer learning python. This algorithm computes the nth fibonacci number using recursion + memoization. I don’t understand why I’m seeing this error “IndexError: list index out of range” when running the program in python. Can anybody help? Thanks a ton!
Advertisement
Answer
I made few changes in your code to get nth Fibonacci no.(there might be other way too)
JavaScript
1
18
18
1
def fibonaci(i,memo):
2
if i == 0 or i == 1:
3
return i
4
5
if memo[i] == -1:
6
memo[i] = fibonaci(i-1,memo) + fibonaci(i-2,memo)
7
8
return memo[i]
9
10
def fibo(n):
11
a = [-1] * n
12
return fibonaci(n-1,a)
13
14
print(fibo(5))
15
print(fibo(10))
16
print(fibo(13))
17
print(fibo(57))
18
And output is :-
JavaScript
1
5
1
3
2
34
3
144
4
225851433717
5