1. 程式人生 > >Python斐波那契例項(多方式)

Python斐波那契例項(多方式)

#方法一

def Fbnq(n):

    if n ==0 or n == 1:
        return 1
    return Fbnq(n-1) +Fbnq(n-2)
print(Fbnq(3))


#方法二

def Fbnq2(n):
    #給斐波那契數列的前兩個元素賦初值
    #同時利用index記錄迴圈進行的下標位置
    index,a,b = 0,1,1
    while index < n-2:
        a,b = b,a+b #這裡b的值等於f(n)
        index +=1
    return b
for i in range(1,11):

    print(fbnq2(i))

#方法三(協程)

def bnq3(n):
a,b=0,1
i=0
while i<n:
yield b?
a,b=b,a+b
 i+=1
for x in fbnq3(20):

print(x)