-
斐波那契数列
斐波那契数列指的是这样一个数列:1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …
这个数列从第三项开始,每一项都等于前两项之和。
- 原生的斐波那切数列 函数fb;
1 def fb(num): 2 if num <= 2: 3 res = 1 4 else: 5 res = fb(num - 1) + fb(num - 2) 6 return res 7 8 ## 9 fb(10) 10 Out[34]: 55 11 fb(3) 12 Out[35]: 2 13 fb(4) 14 Out[36]: 3
2.计算下算出结果所需的时间,函数usetime
1 import time 2 def usetime(fb, num): 3 ts = time.time() 4 print("斐波那契额数列第%d位结果为:%d" % (num, fb(num))) 5 td = time.time() 6 print("菲波那切函数%s用时:%s" % (fb.__name__, str(td - ts)))
usetime(fb,30) 斐波那契额数列第30位结果为:832040 菲波那切函数fb用时:0.26912498474121094 usetime(fb,35) 斐波那契额数列第35位结果为:9227465 菲波那切函数fb用时:2.9368109703063965
3.使用cache功能,为递归增加缓存功能
fb 是使用装饰器增加cache功能
1 #!/usr/local/bin python 2 # -*-coding:utf-8-*- 3 ''' 4 5 ''' 6 import time 7 from functools import wraps 8 9 10 def cache(func): 11 caches = {} 12 @wraps(func) 13 def wrapper(num): 14 if num in caches: 15 pass 16 else: 17 caches[num] = func(num) 18 return caches[num] 19 20 return wrapper 21 22 @cache 23 def fb(num): 24 if num <= 2: 25 res = 1 26 else: 27 res = fb(num - 1) + fb(num - 2) 28 return res 29 30 31 def fb2(num): 32 if num <= 2: 33 res = 1 34 else: 35 res = fb2(num - 1) + fb2(num - 2) 36 return res 37 38 39 def usetime(fb, num): 40 ts = time.time() 41 print("斐波那契额数列第%d位结果为:%d" % (num, fb(num))) 42 td = time.time() 43 print("菲波那切函数%s用时:%s" % (fb.__name__, str(td - ts))) 44 45 46 if __name__ == "__main__": 47 usetime(fb, 36)
usetime(fb,36) 斐波那契额数列第36位结果为:14930352 菲波那切函数fb用时:1.9073486328125e-05 usetime(fb2,36) 斐波那契额数列第36位结果为:14930352 菲波那切函数fb2用时:4.814869165420532 usetime(fb,300) 斐波那契额数列第300位结果为:222232244629420445529739893461909967206666939096499764990979600 菲波那切函数fb用时:0.0009541511535644531
以上是cache添加前后的对比结果,以上功能实现 参考慕课网著名python讲师刘硕
浙公网安备 33010602011771号