1. 程式人生 > >python學習第四十四天斐波那契數列和yield關鍵詞使用

python學習第四十四天斐波那契數列和yield關鍵詞使用

數學 開始 pri .cn 文章 int 斐波那契數 a + b 第一個

斐波那契數列是數學中的常見的算法,第一個第二個不算,從第三個開始,每個數的都是前面兩個數的和,使用yield關鍵詞把生成的數列保存起來,調用的時候再調用,下面舉例說明一下

def fab(max):
  n, a, b = 0, 0, 1
  while n < max:
    yield b
    # print b
    a, b = b, a + b
    n = n + 1

調用方式

>>> for n in fab(5):
... print n
...
1
1
2
3
5

在這裏yield起到關鍵的作用

文章來自 http://www.96net.com.cn

python學習第四十四天斐波那契數列和yield關鍵詞使用