The onacci Fibonacci series is simple. It is a recursion. It may be used to learn any programming language.
This time, python is no exception. The most basic recursion (as shown in the following figure) is too inefficient, as long as n digits are too long to be computed; the computation function is saved to a dict, which is directly used for subsequent computation. In this way, memo is used. As shown in the following fib2 function, the efficiency is greatly improved.
When n = 10 or less, the running time of FAB1 and fab2 is very short, but it is too obvious when n = 40, and it takes 35 seconds to run FAB1, fab2 only takes 0.00001 seconds to run.
When n = 40, the output is as follows:
The code is as follows: |
Copy code |
Jay @ jay-linux :~ /Workspace/python. git/py2014 $ python fibonacci. py 16:28:35. 176396 Fiber 1 (40) = 102334155 16:29:10. 479953 Fiber 2 (40) = 102334155 16:29:10. 480035 |
The two functions that calculate the Fibonacci series are as follows: https://github.com/smilejay/python/blob/master/py2014/fibonacci.py
The code is as follows: |
Copy code |
Import datetime Def fiber 1 (n ): If n = 0: Return 0 Elif n = 1: Return 1 Else: Return fiber 1 (n-1) + Fiber 1 (n-2) Known = {0: 0, 1: 1} Def fiber 2 (n ): If n in known: Return known [n] Res = fiber 2 (n-1) + fiber 2 (n-2) Known [n] = res Return res If _ name _ = '_ main __': N = 40 Print (datetime. datetime. now ()) Print ('fig (% d) = % d' % (n, Fig (n ))) Print (datetime. datetime. now ()) Print ('fig (% d) = % d' % (n, Fig (n ))) Print (datetime. datetime. now ()) |