python实现斐波那契数列
斐波那契数列:第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