Created
December 29, 2011 05:34
-
-
Save mactkg/1532140 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#フィボナッチ数列のジェネレータ | |
def fib(max): | |
a, b, = 0, 1 #こういう代入も出来ます | |
while a < max | |
yield a | |
a, b = b, a + b | |
f = fib(6) | |
next(f) #=> 0 | |
next(f) #=> 1 | |
next(f) #=> 1 | |
next(f) #=> 2 | |
next(f) #=> 3 | |
next(f) #=> 5 | |
next(f) #=> StopIteration | |
for n in fib(150): | |
print(n) | |
#=>0 1 1 2 3 5 8 13 21 34 55 89 144 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
説明
前回とは違って終わりのあるジェネレータを作ってみる。
フィボナッチ数列を指定された数字まで生成するジェネレータだ。
もしwhileを抜けて関数が終わりに来ると、StopIterationという例外が出てくる。
StopIterationは例外なのでexceptでcatchもできる。
for文はStopIterationが来ると終わりになるので、それを考えればfor文のところにぶち込んでしまえば便利に使うことができる。二番目がその例だ。
参考文献
http://diveintopython3-ja.rdy.jp/generators.html#a-fibonacci-generator