斐波那契數列:第0項是0,第1項是第一個1。這個數列從第3項開始,每一項都等於前兩項之和。如下:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368.....
實現1:
if __name__ == '__main__':
f = [0,1]
print(type(f))
for n in range(2,20):
# f[n]=f[n-1]+f[n-2] # 會報錯IndexError: list assignment index out of range;
f.append(f[n - 1] + f[n - 2])
# print(f)
n = n + 1
print(f)
結果如下:
<class 'list'>
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
Process finished with exit code 0
實現2:
# Fibonacci series: 斐波納契數列
# 兩個元素的總和確定了下一個數
a, b = 0, 1
while b < 1000:
print(b, end=',') # 關鍵字end可以用於將結果輸出到同一行,或者在輸出的末尾添加不同的字符
a, b = b, a+b
結果如下:
1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
Process finished with exit code 0