python斐波那契数列
程序员文章站
2022-05-15 14:09:06
...
python斐波那契数列
递归方法:
"""斐波那契数列的递归计算"""
def recur_fibo(num):
if num<=1:
return num
else:
return (recur_fibo(num-1)+recur_fibo(num-2))
if __name__ == '__main__':
number=int(input("请输入你要输出的斐波那契数列的项数"))
if number>=0:
for i in range(number):
print(recur_fibo(i))
else:
print ("请输入正整数")
非递归方法:
def function(num):
"""实现斐波那契数列函数"""
number1=0 #第一项
number2=1 #第二项
count=2
if num==1:
print(number1)
else:
print(number1,",",number2,end=",")
while count<num:
nth=number1+number2
print(nth,end=",")
number1=number2
number2=nth
count+=1
if __name__ == '__main__':
number=int(input("请输入你要就算的斐波那契数列的项数"))
if number>=0:
function(number)
else:
print ("请输入一个正整数")
程序运行结果截图:
上一篇: 2020程序员节首届哔哩哔哩安全挑战赛