递归版本:函数在执行的过程中调用了本身,通常用于分治法,即将问题拆分为规模较小的子问题
def fib1(n):
return 1 if n<=1 else fib1(n-1)+fib2(n-2)
list(map(fib1,range(10)))
输出:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
非递归版本:
def fib2(n):
a,b=1,1
for _ in range(n):
a,b=b,a+b
return a
tmp = map(fib2,range(10))
list(tmp)
缓存版本:
def fib3(n,cache={0:1,1:1}):
try:
return cache[n]
except KeyError:
cache[n]=fib3(n-1)+fib3(n-2)
return cache[n]
list(map(fib3,range(10)))
1017

被折叠的 条评论
为什么被折叠?



