题目-006:斐波那契数列
在数学上,费波那契数列是以递归的方法来定义:F(1)=1,F(2)=1, F(n)=F(n-1)+F(n-2)(n>=2,n∈N*)点击打开链接
- 分析:递归计算
- Python版本:Python 3.6.5
代码1:直接递归计算,得出结果
#! usr/bin/python
#! -*- coding: utf-8 -*-
def fibonacci_sequence():
length = int(input("please input the length of Fibonacci sequence:"))
if length < 1:
print("input illegal,try to input again")
else:
if length == 1:
data = [1]
elif length == 2:
data = [1,1]
elif length > 2:
data = [1, 1]
for i in range(2,length):
count = data[i-1] + data[i-2]
data+=[count]
print("the list you need is:",data)
while True:
fibonacci_sequence()
please input the length of Fibonacci sequence:-9
input illegal,try to input again
please input the length of Fibonacci sequence:6
the list you need is: [1, 1, 2, 3, 5, 8]
please input the length of Fibonacci sequence:9
the list you need is: [1, 1, 2, 3, 5, 8, 13, 21, 34]