python乱炖.1——斐波那契数列代码
学习笔记系列
递归方法
无缓存方法
def fib(n):
if n == 0 or n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2)
print(fib(35))
有缓存(动态规划)
第一个来自 https://edu.csdn.net/skill/python/python-3-1?typeId=17334
cache = {}
def fib(number):
if number in cache:
return cache[number]
if number == 0 or number == 1:
return 1
else:
cache[number] = fib(number - 1) + fib(number - 2)
return cache[number]
if __name__ == '__main__':
print(fib(35))
def fib(n):
fib_sequence = [1, 1]
for i in range(2, n + 1):
fib_sequence.append(fib_sequence[i - 1] + fib_sequence[i - 2])
return fib_sequence[n]
print(fib(35))
迭代
这个就是直接循环计算了
def fib(n):
a, b = 1, 1
for _ in range(n):
a, b = b, a + b
return a
print(fib(35))
矩阵幂法
import numpy as np
def fib(n):
F = np.matrix([[1, 1], [1, 0]])
return (F**n)[0, 1]
print(fib(35))
这里附上原理
就结束啦!