递归的算斐波那契数列,为什么用lambda实现会比用def实现效率高?
测试代码如下:
python
import time def fibonacci(n): if n < 2: return n return fibonacci(n - 2) + fibonacci(n - 1) aaa = time.time() print fibonacci(35) print time.time() - aaa print '--------------------------------' fib=lambda n:1 if n<=2 else fib(n-1)+fib(n-2) bbb = time.time() print fib(35) print time.time() - bbb
我本机的测试结果如下:
9227465 6.27800011635 -------------------------------- 9227465 4.00600004196
def定义函数递归的调用会有开销,那么lambda为什么会快一些呢?
wind32
11 years, 4 months ago