1. 程式人生 > >python實現斐波那契數列筆記

python實現斐波那契數列筆記

log 得到 while span style mage lis nbsp images

斐波那契數列即著名的兔子數列:1、1、2、3、5、8、13、21、34、……

數列特點:該數列從第三項開始,每個數的值為其前兩個數之和,用python實現起來很簡單:

a=0
b=1
while b < 1000:
    print(b)
    a, b = b, a+b

輸出結果:

技術分享

這裏 a, b = b, a+b 右邊的表達式會在賦值變動之前執行,即先執行右邊,比如第一次循環得到b-->1,a+b --> 0+1 然後再執行賦值 a,b =1,0+1,所以執行完這條後a=1,b=1

a=0
b=1
while b < 1000:
    print(b,end=,)#
end 可以將print輸出到同一行並以 ,號結尾 a, b = b, a+b

輸出結果:

技術分享

遞歸方式實現斐波那契數列 前n項:

# 遞歸方式實現 生成前20項
lis =[]
for i in range(20):
    if i ==0 or i ==1:#第1,2項 都為1
        lis.append(1)
    else:
        lis.append(lis[i-2]+lis[i-1])#從第3項開始每項值為前兩項值之和
print(lis)

運行結果

技術分享

python實現斐波那契數列筆記