巧用Hint
一般計(jì)算fibonacci的方法:
1 def fibonacci (n): 2 if n == 0 or n == 1: 3 return 1 4 else: 5 return fibonacci(n-1) + fibonacci(n-2)這樣的?call graph for fibonacci with n=4:
當(dāng)計(jì)算?fibonacci(30)的時(shí)候還可以,當(dāng)計(jì)算?fibonacci(50)的時(shí)候就很慢了。
好的方法是:用dict記錄下來之前計(jì)算過的值。
A previously computed value that is stored for later?use is called a hint.
好的方法是:
previous = {0:1, 1:1} def fibonacci(n):if previous.has_key(n):return previous[n]else:newValue = fibonacci(n-1) + fibonacci(n-2)previous[n] = newValuereturn newValue這樣就很快了。
?
類似的計(jì)算階乘:
previous = {1:1,2:2} def n(i):if previous.has_key(i):return previous[i]else:newValue = i*n(i-1)previous[i] = newValuereturn previous[i]---How to Think Like a Computer Scientist(Learning with Python)
轉(zhuǎn)載于:https://www.cnblogs.com/eagle-chen/p/4260744.html
總結(jié)
- 上一篇: querydsl动态 sql_Sprin
- 下一篇: TotoiseSVN 使用参考文章