3 kinds of realization of the sequence of Fibonacci-Tangent series

Source: Internet
Author: User

The Fibonacci number , also known as the Fibonacci sequence (Italian: Successione di Fibonacci), also known as the Golden Division Series, Fibonacci, Fibonacci, Fisher series, refers to such a series: 0, 1, 1, 2, 3, 5, 8, 13, 21st...... In mathematics, the Fibonacci sequence is defined as the following recursive method: F0=0,f1=1,fn=fn-1+fn-2 (n>=2,n∈n*), in words, is the Fibonacci sequence column starting with 0 and 1, after which the Fibonacci sequence coefficients are added by the previous two numbers.


1, implemented in a recursive way, with low efficiency

in [/]: def fib (n):
..: If n = 0:
...: return 0
..: If n ==1:
...: Return 1
..: Else:
...: return fib (n-1) + fib (n-2)
...:

in [+]: fib (5)
OUT[26]: 5


in [+]: fib (10)
OUT[27]: 55


2, by means of a for loop

in [[]: Def fib (n):
..: A,b = 0,1
...: For I in range (n):
..: A,b = b,a+b
..: Return a


in [[]: Def fib (n):
..: A,b = 0,1
..: LST = []
...: For I in range (n):
..: Lst.append (a)
..: A,b = b,a+b
...: Return LST


3, through the generator of the way to achieve

In [7]: def fib (n):
..: A,b = 0,1
...: For I in range (n):
..: Yield A
..: A,b = b,a+b


In [9]: for x in Fib (10):
..: Print (x)
...:
0
1
1
2
3
5
8
13
21st
34


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.