Python练习题-006

题目-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]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值