Recursive method for calculating Fibonacci sequences (recursion Fibonacci Python)

Source: Internet
Author: User

First science what is called the Fibonacci sequence, the following excerpt from the Baidu Encyclopedia:

The Fibonacci sequence (Fibonacci sequence), also known as the Golden Section, was introduced by the Italian mathematician Leonardo's Fibonacci (Leonardoda Fibonacci) as an example of a rabbit reproduction, referring to such a Number of columns: 1, 1, 2, 3, 5, 8, 13, 21, 34 ... This sequence starts with the 3rd item and each item is equal to the sum of the first two items.

According to the above definition, Python defines a function for calculating the number of nth items in the Fibonacci sequence:

def fib_recur (n):

return n
Else
return (FIB (n-1) + fib (n-2)) #每一项返回的结果都是前两项之和

Call this function to try it:

Print (FIB (5))

The result is:

5

If you want to list the Fibonacci sequence to Nth, the code is as follows:

Num=int (Input ("Would you like to list several Fibonacci numbers?") "))
If num<=0:
Print ("Please enter a positive integer")
Else
Print ("Fibonacci sequence:")
For I in Range (num+1):
Print (FIB (i))

The results of the operation are as follows:

would you like to make a list of Fibonacci sequences? 5

Fibonacci Sequence:
0
1
1
2
3
5

Reference: MIT Open Class: Introduction to Computer Science and Programming (4th lesson)

Attached: The Fibonacci sequence is calculated without a recursive method

Num=int (Input ("Would you like to list several Fibonacci numbers?") "))
#先定义第一项和第二项
Num1=1
Num2=1
While num1<num+1:
Print (NUM1)
Num1,num2=num2,num1+num2 #把第二项的值赋予第一项, the value of the third item is assigned to the second item, and so on

The results of the operation are as follows:

Would you like to make a list of Fibonacci sequences? 5
1
1
2
3
5

Recursive method for calculating Fibonacci sequences (recursion Fibonacci Python)

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.