Home >Backend Development >Python Tutorial >Write Fibonacci sequence using python function

Write Fibonacci sequence using python function

hzc
hzcOriginal
2020-07-03 15:40:2120660browse

Fibonacci Sequence, also known as the Golden Section Sequence, was introduced by mathematician Leonardo Fibonacci using the example of rabbit reproduction, so it is also called the "Rabbit Sequence", which refers to Such a sequence: 1, 1, 2, 3, 5, 8, 13, 21, 34,... In mathematics, the Fibonacci sequence is defined recursively.

Write Fibonacci sequence using python function

For those who are learning programming languages, the Fibonacci sequence will be one of the most classic functions. Today I will use Python to teach you Let’s talk about how to implement this classic function simply and crudely.

Before implementing it, let me first introduce to you the principle of Fibonacci sequence. The original question is a rabbit breeding problem. Simply put, the latter term is equal to the sum of the first two terms, that is, f(x) =f(x-1) f(x-2), the first term can be 0 or 1.

The following are two commonly used methods. They may not be as concise as others have written, so please forgive me!

The first: non-recursive method, using a combination of indexing and while loops

# Starting from zero, output the first n items of the Fibonacci sequence
# Define Fibonacci Naqi function
def fibo(x):
#Initialize the first two items
m=0
n=1
# Use list to store
l=[0,1]
# Set the initial item
i=2
# Use a while loop to perform operations. The principle is: the last item is equal to the sum of the previous two items
while i# m n is assigned to n
n=m n
# Add n to the list
l.append(n)
# Assign the previous item of the list to m
m =l[i-1] through the index
#Achieve the condition for exiting the loop through self-adding
i=i 1
#Print out the list
print(l)
# Call the function
fibo(10)

Second: Recursive implementation, this is the classic model

# Starting from scratch, output the n-th Fibonacci sequence

def fibo(x):
if x==1:
return 0
elif x==2:
return 1
elif x>2:
return fibo(x-1)+fibo(x-2)
else:
print("输入错误,请重新输入!")

Recommended tutorial: "Python Tutorial"

The above is the detailed content of Write Fibonacci sequence using python function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn