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)