Python-斐波那契数列

# if判断

nterms = 10   # 需要显示的数列位数
n1, n2 = 1, 1  # 第一和第二项
count = 3
if nterms <= 0:     # 判断输入的值是否合法
   print("请输入一个正整数。")
elif nterms == 1:
   print("斐波那契数列:")
   print(n1)
else:
   print("斐波那契数列: ", end='')
   print(n1, n2, end=" ")
   while count <= nterms:
       nth = n1 + n2
       print(nth, end=" ")
       n1, n2 = n2, nth     # # 更新值
       count += 1

 

# 循环

a = 0
b = 1
print('斐波那契数列: ', end='')
while b <= 1000:
    print(b, end=' ')
    a, b = b, a+b

 

# yield

def Fibo_Yield_tool(n):
    a, b = 0, 1
    while n > 0:
        yield b
        a, b = b, a + b
        n -= 1

def Fibo_Yield(n):
    # return [f for i, f in enumerate(Fibo_Yield_tool(n))]  # 列表解析,这种方式转换速度很慢
    return list(Fibo_Yield_tool(n))  # 直接转化为list,这种方式比较快

if __name__ == '__main__':
    a = Fibo_Yield(10)     # n代表位数
    print(a)

 

# 递归

def Fibo_tool(n):
    if n <= 0:
        return 0
    elif n == 1:
        return 1
    else:
        return Fibo_tool(n - 1) + Fibo_tool(n - 2)

def Fibo_Recursion(n):
    result_list = []
    for i in range(1, n + 1): result_list.append(Fibo_tool(i))
    return result_list

if __name__ == '__main__':
    a = Fibo_Recursion(10)  # 代表数列的位数
    print(a)

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值