斐波那契數列 yield 和list 生成

def fab_demo4(max):
    a,n,b = 0,0,1
    while n < max:
        yield b  # 生成器走到這一步返回b,須要再次調用才能繼續執行

        a,b = b,a+b
        n += 1

f = fab_demo4(10)  # 調用了fab_demo4方法,返回內存地址
print(list(f))  # lsit()將地址內數據顯示,有一次調用方法,讓yield後面的代碼執行,指導循環結束

  

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

 

下面是我一之前計算斐波那契數列的方法python

# [] 列表實現
def fibonacci(num):
    fibs = [0, 1]
    for i in range(num - 2):
        fibs.append(fibs[-2] + fibs[-1]) # 倒數第二個+倒數第一個數的結果,追加到列表
    print(fibs)
fibonacci(10)

  

# yield 實現
def fab_demo4(max):
    a,n,b = 0,0,1
    while n < max:
        yield b
        #print b
        a,b = b,a+b
        n+=1
print(next(fab_demo4(10)))
for i in fab_demo4(8):
    print(i)

  

1
1
1
2
3
5
8
13
21

Process finished with exit code 0
相關文章
相關標籤/搜索