deffib1(n):# a = b = 1a =1# 初始化两个变量a和b,它们都等于1b =1for i inrange(n-2):# 对于从0到n-2的每个i,执行以下操作a, b = b, a + b # 将b的值赋给a,将a+b的值赋给breturn b # 返回b的值fib1(101)# 调用fib1函数,传入参数101,并打印结果# 返回结果:573147844013817084101
deffib4(n, a=1, b=1):# 函数调用次数代替循环次数if n <3:# 3return ba, b = b, a+breturn fib4(n-1, a, b)# fib3(3-1, 1, 2) => 2fib4(35)# 返回结果:9227465
%timeit fib1(35)# 返回结果:554 ns ± 6.62 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
%timeit fib4(35)# 返回结果:1.32 µs ± 8.48 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)