Help us understand the problem. What is going on with this article?

ジェネレータとイテレータでフィボナッチ数列を計算する

More than 1 year has passed since last update.
  • yieldはジェネレータ関数のループの中に書く
  • ジェネレータ関数のループ以外の部分は1回しか呼び出されない
  • ジェネレータ関数はイテレータを返す
  • イテレータからnextメソッドによって繰り返し要素を取得できる
  • nextメソッドを呼べば呼ぶほど無限に値を生成できる
fibonacci.py
#!/usr/bin/python

# ジェネレータを定義する
def fibonacci():
    a = 0 # 初期設定
    b = 1 # 初期設定

    while True:
        yield b # ジェネレータ関数のループの中にyieldを書く
        a, b = b, a + b

# ジェネレータはイテレータを返す
fib = fibonacci()

#リスト内包表記でイテレータの各要素を順に配列に入れる
fib_array = [fib.next() for i in range(10)] 

print fib_array
  • 計算結果
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away