Python產生器(2)—— 斐波拉契數列

來源:互聯網
上載者:User

標籤:##   stop   否則   max   pyc   式表   ack   logs   異常   

斐波那契數列並不能用列表生產式表示,但能夠用函數得出:

 1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 def fib(max): 4     n,a,b = 0,0,1 5     while n < max: 6         print(b) 7         a,b = b,a + b  #初始a=0、b=1,a=b和b=a+b可理解為同時執行,即a=1、b=0+1=1 8         n = n +1 9     return ‘OK‘10 11 fib(9)

輸出:

1
1
2
3
5
8
13
21
34

##################################華麗的分割線##########################################

將以上產生斐波拉契數列函數中的print (b)改為yield b則變成產生器

 1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 def fib(max): 4     n,a,b = 0,0,1 5     while n < max: 6         yield b 7         a,b = b,a + b 8         n = n + 1 9     return ‘OK‘10 11 fib(9)

print(fib(9))輸出:

<generator object fib at 0x00000000010E6A40>

##################################華麗的分割線##########################################

 1 f = fib(9) 2 print(f.__next__()) 3 print(f.__next__()) 4 print(f.__next__()) 5 print(f.__next__()) 6 print(f.__next__()) 7 print(f.__next__()) 8 print(f.__next__()) 9 print(f.__next__())10 print(f.__next__())11 print(f.__next__())12 print(f.__next__())13 print(f.__next__())

使用next方法調用要注意調用次數,否則會出現報錯 或 使用異常處理

1
1
2
3
5
8
13
21
34
Traceback (most recent call last):
File "C:/Users/chenshiyang/PycharmProjects/5.py", line 24, in <module>
print(f.__next__())
StopIteration: OK

##################################華麗的分割線##########################################

加入異常處理玩法:

 1 #_*_coding:utf-8_*_ 2 #__author__ = "csy" 3 def fib(max): 4     n,a,b = 0,0,1 5     while n < max: 6         yield b 7         a,b = b,a + b 8         n = n + 1 9     return ‘Finish‘10 11 f = fib(9)12 while True:13     try:14         x = next(f)15         print(‘f:‘,x)16     except StopIteration as e:17         print(‘已經到頭了‘, e.value)18         break

輸出:

f: 1
f: 1
f: 2
f: 3
f: 5
f: 8
f: 13
f: 21
f: 34
已經到頭了 Finish

Python產生器(2)—— 斐波拉契數列

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.