最近的动态编程引起了我的兴趣。因此,我使用动态编程概念在fibonacci系列上编写了代码,但是每次执行时,我都会遇到数组超出索引范围的情况。我尽力弄清楚了,但无法解决。从错误中,我认为索引在上一次迭代时超出范围。这是我的代码:
def fibo(n) :
# len(mem) being shorter than n will indicate that the position is not filled(memoized)
# if it is equal then is has the required value it wont have to calculate res = fibo(n-1)+ fibo(n-2)
if len(mem) == n :
return mem[n]
#General cases
if n == 1 or n == 2 :
res = 1
elif n == 0 :
res = 0
else :
res = fibo(n-1)+ fibo(n-2)
#Here the len(m) should be n-1 and thus we append the value of 'res'so at one point we can return it instead of calculating
mem.append(res)
return res
#Start of Program
n = int(input("Enter the position :"))
#Defining mem as a list
mem = []
print(fibo(n))
您需要先在列表中添加1:
mem = [1]
for i in range(1,10):
print(fibo(i))
1
1
2
3
5
8
13
21
34