Python implements the Fibonacci sequence

Source: Internet
Author: User

The Fibonacci sequence is in the form of the last digit, the sum of the first two digits, and so on.

The performance is as follows: 1 2 3 5 8 13 21 34 55 .....

#-*-Coding:utf-8-*-# File: The iterator implements the Fibonacci sequence. py# author:huxianyong# date:2018-07-10 09:20# method One, use a class iterator to do the Fibonacci sequence import t Imeclass foo:def __init__ (self,m,n): Self.n=n self.m=m def __iter__ (self): return self def __next__ (self): if self.m > 500:exit () self.n,self.m = self.m,self.n+self.m return sel F.nf1=foo (All) for I in F1:time.sleep (1) print (i)


#方法二: Fibonacci sequence in the form of a function formula

Import timedef Item (NUM): if num = = 0:res = 0 elif num = = 1:res = 1 else:res = Item (num- 1) +item (num-2) return resi=0while i < 9:print (item (i)) Time.sleep (1) i+=1


Method Three: Iterating over the form of the Fibonacci sequence added to the list

def fibo (num): Numlist = [0,1] for I in range (num-2): Numlist.append (Numlist[-2] + numlist[-1]) return n Umlistprint (Fibo) def Fibo (n): x, y = 0, 1 while (n): X,y,n = y,x+y,n-1 return XPrint (Fibo (10))


Python implements the Fibonacci sequence

Related Article

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.