python 給定n,返回n以內的斐波那契數列

來源:互聯網
上載者:User

標籤:end   斐波那契   images   while   tor   view   elf   gif   分享   

方式一:函數

1 def fabs(n):2     a, b = 0, 13     while b < n:4         print(b, end=‘ ‘)5         a, b = b, a+b6 7 fabs(1000)
View Code

方式二:列表

1 result = [0, 1]2 3 def fabs(n):4     while n-result[-1] > result[-2]:5         result.append(result[-2] + result[-1])6 7 fabs(100)8 print(result)
View Code

方式三:類

 1 class Fabs: 2      3     def __init__(self, max): 4         self.max = max 5         self.a, self.b = 0, 1 6  7     def __iter__(self): 8         return self 9 10     def next(self):11         if self.b<self.max:12             r = self.b13             self.a, self.b = self.b, self.a+self.b14             return r15 16 17 f1 = Fabs(1000)18 m = f1.next()19 while m:20     print(m, end=‘ ‘)21     m = f1.next()
View Code

方式四:產生器

1 def fabs(n):2     a, b = 0, 13     while b<n:4         yield b5         a, b = b, a+b6 7 if __name__ == ‘__main__‘:8     for i in fabs(1000):9         print(i, end=‘ ‘)
View Code

 

python 給定n,返回n以內的斐波那契數列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.