Skip to content

Instantly share code, notes, and snippets.

@mactkg
Created December 29, 2011 05:34
Show Gist options
  • Save mactkg/1532140 to your computer and use it in GitHub Desktop.
Save mactkg/1532140 to your computer and use it in GitHub Desktop.
#フィボナッチ数列のジェネレータ
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
@mactkg
Copy link
Author

mactkg commented Dec 29, 2011

説明

前回とは違って終わりのあるジェネレータを作ってみる。
フィボナッチ数列を指定された数字まで生成するジェネレータだ。
もしwhileを抜けて関数が終わりに来ると、StopIterationという例外が出てくる。
StopIterationは例外なのでexceptでcatchもできる。
for文はStopIterationが来ると終わりになるので、それを考えればfor文のところにぶち込んでしまえば便利に使うことができる。二番目がその例だ。

参考文献

http://diveintopython3-ja.rdy.jp/generators.html#a-fibonacci-generator

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment