Python implements the Fibonacci sequence (Fibonacci sequence)

Source: Internet
Author: User

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)

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.