方法一:不导入任何帮助模块计算数列
FIB = [1]
def fib(n):
"""1 1 2 3 5 8 13 21 34 55"""
if len(FIB) >= n: return FIB[n - 1]
return n if n < 2 else (fib(n - 1) + fib(n - 2))
def cache_fib(n):
fl = len(FIB)
if fl < n:
for i in range(fl + 1, n + 1):
FIB.append(fib(i))
return FIB[n - 1]
方法二:导入functools模块下的lru_cache方法计算数列
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
"""0 1 1 2 3 5 8 13 21 34 55"""
return n if n < 2 else fib(n-1) + fib(n-2)
网友评论