Comparison of two methods for solving the Fibonacci series python

Source: Internet
Author: User
Tags comparison datetime

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 ())

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.