Exercise 6: Fibonacci Series)

Source: Internet
Author: User

Question: Fibonacci series.

Program analysis: the Fibonacci sequence, also known as the Golden series, refers to a series like this: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 ,.......

In mathematics, the Fibonacci sequence is defined by recursion:

F0 = 0 (n = 0)
F1 = 1 (n = 1)
Fn = f [n-1] + F [N-2] (n => 2)
---------------------
Method 1: Recursive Computing

 1 def fibonacci(month): 2     if month == 1: 3         return 1 4     elif month == 2: 5         return 1 6     else: 7         return fibonacci(month-1)+fibonacci(month-2) 8  9 a =fibonacci(35)10 print(a)

Method 2: Use the WHILE LOOP

1 def FAB (n): 2 n1 = 1 3 n2 = 1 4 N3 = 0 5 if n <1: # conditional judgment, if n <, will directly return-1 6 Return-1 7 while (n-2)> 0: 8 N3 = N1 + N2 9 n1 = n210 n2 = n311 N-= 112 return n313 14 N = FAB (20) 15 print (N)

To change it to output a specified number of Fibonacci series, you only need to return the results to the list, which can be directly counted.

 1 def fib(n): 2     if n == 1: 3         return [1] 4     if n == 2: 5         return [1,1] 6     fibs = [1,1] 7     for i in range(2,n): 8         fibs.append(fibs[-1]+fibs[-2]) 9     return fibs10 11 print(fib(5))

 

Exercise 6: Fibonacci Series)

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.