斐波那契数列的两种解法:1.递归,2.字典
1.递归求解斐波那契数列数列
def fbnq(n):
if n ==0:
return 0
elif n ==1:
return 1
else:
return fbnq(n-2) + fbnq(n-1)
dic={}
for n in range(30):
dic[n] = fbnq(n)
print(dic)
{0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5, 6: 8, 7: 13, 8: 21, 9: 34, 10: 55, 11: 89, 12: 144, 13: 233, 14: 377, 15: 610, 16: 987, 17: 1597, 18: 2584, 19: 4181, 20: 6765, 21: 10946, 22: 17711, 23: 28657, 24: 46368, 25: 75025, 26: 121393, 27: 196418, 28: 317811, 29: 514229}
2.解决斐波那契数列用到了递归的思想,缺点就是时间开销和空间开销比较大,因为每一个数字都重复计算了很多次,解决方法是把计算出来的数值保存到字典当中,避免重复计算,下面贴出代码。
def fbnq(n):
dic = {0: 0, 1: 1}
if n in dic:
return dic[n]
else:
for i in range(2,n+1):
dic[i] = dic[i-2] + dic[i-1]
return dic
print(fbnq(30))
{0: 0, 1: 1, 2: 1, 3: 2, 4: 3, 5: 5, 6: 8, 7: 13, 8: 21, 9: 34, 10: 55, 11: 89, 12: 144, 13: 233, 14: 377, 15: 610, 16: 987, 17: 1597, 18: 2584, 19: 4181, 20: 6765, 21: 10946, 22: 17711, 23: 28657, 24: 46368, 25: 75025, 26: 121393, 27: 196418, 28: 317811, 29: 514229, 30: 832040}
本文地址:https://blog.csdn.net/qq_36079986/article/details/110246881
上一篇: cv2.Tracker
下一篇: 【统计学习方法】学习笔记--k近邻法