Using Python to implement the Fibonacci sequence (Fibonacci sequence)
Fibonacci sequences are like 1,1,2,3,5,8,13, and so on. In other words, the next value is the sum of the first two values in the sequence. Write a function, given n, to return the nth Fibonacci number. For example, 1 returns 1
6 return 8
I chose two methods, one to turn list into a queue and the other to use a ring queue. Not much to say, directly on the code; I'll explain why this is going to happen.
The first is how to use a queue:
1 deffibonacciseq (num):2Fibonacciseqlist = []3 forIinchxrange (0, num):4 ifLen (fibonacciseqlist) < 2:5Fibonacciseqlist.append (1)6 Continue7Fibonacciseqlist.append (fibonacciseqlist[-1]+fibonacciseqlist[-2])8 fibonacciseqlist.pop (0)9 returnFIBONACCISEQLIST[-1]
The second one also uses the list, but it is a list that has already been initialized:
1 deffibonacciseq_c (num):2Fibonacciseqlist = [1,1,1]3Writeposi =04 ifNum <= 2:5 returnFibonacciseqlist[num]6 forIinchXrange (2, num):7Writeposi = i% 38Fibonacciseqlist[writeposi] = fibonacciseqlist[writeposi-1] + fibonacciseqlist[writeposi-2]9 returnFibonacciseqlist[writeposi]
Both of these, to reach the same directory, are returning the nth Fibonacci number
The following is an explanation of the above code:
1. Why is the queue used?
Because, when the number you are asking is a large number, you will find that simply using list to fill the memory
2. Why use a ring queue?
Because, when the amount of computation is greater, the ring queue will take less time than the first, although it can be a millisecond level. Ha ha haha
Python implements the Fibonacci sequence (Fibonacci sequence)