Python basic algorithm collection (1) (ordinary algorithm) Fibonacci sequence

The way to learn Python from JAVA to pedestrian
Fibonacci series refers to a series of numbers:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, ...
We will find that from the first The three numbers start to be equal to the sum of the first two numbers, ie 2=1+1, then we can put the first two numbers in the list first, and then add the following numbers in turn using the append method of the list To the back of the list, list1.append(Num)
can first assign the first 0 and 1 to a and b respectively, and then calculate the sum of these two numbers and assign it to the variable c, that is, c=a+b, since the third The number is equal to the sum of the first two numbers, then the Nth number is equal to the sum of (N-2) + (N-1), then the number must be moved back one position (equivalent to a pointer), that is, a=b, b=c This completes the exchange of numbers and assigns values ​​to a and b at the same time. In this way, the value of a+b can be calculated again and assigned to the variable c.
Finally, you need to add the value of variable C to the list, and finally print it out to complete the printing of the Fibonacci sequence. The entire code is as follows:

#普通算法
a=0
b=1
e=[a,b]
print('(普通算法)打印斐波那契数列:')
n=int(input('请输入斐波那契数列的长度:'))
for i in range(n):
    c=a+b
    a=b
    b=c
    e.append(c)
print (e)

operation result:
Insert picture description here

The next issue is to print the Fibonacci sequence recursively.

Guess you like

Origin blog.csdn.net/weixin_43115314/article/details/113922702