斐波那契数列

斐波那契数列:0,1,1,2,3,5,8,13,...,求该数列第n项数字。

  • 数列前两个数字 f(1)=0,f(2)=1
  • 数列的每个数字是前两个数字之和

以下是两种不同的方法求第n项数字:循环迭代、递归

python 复制代码
# 斐波那契数列:0,1,1,2,3,5,8,13,......,求该数列第n项数字

# 循环迭代
def fib(n: int) -> tuple:
    """
    斐波那契数列:循环
    :param n: 项数
    :return:
    """
    n1, n2 = 0, 1
    n_list = [n1, n2]
    for item in range(n - 2):
        temp = n2
        n2 = n1 + n2
        n1 = temp
        n_list.append(n2)

    return n2, n_list


# 递归
def fib_plus(n: int) -> int:
    """
    递归
    :param n:
    :return:
    """
    # 终止条件
    if n == 1 or n == 2:
        return n - 1
    # 递归调用
    result = fib_plus(n - 1) + fib_plus(n - 2)
    return result


if __name__ == '__main__':
    num = fib(10)
    print(num)  # (34, [0, 1, 1, 2, 3, 5, 8, 13, 21, 34])

    num = fib_plus(10)
    print(num)   # 34
相关推荐
noravinsc2 分钟前
人大金仓数据库 与django结合
数据库·python·django
郭尘帅6664 分钟前
Vue3中实现轮播图
开发语言·前端·javascript
豌豆花下猫9 分钟前
Python 潮流周刊#102:微软裁员 Faster CPython 团队(摘要)
后端·python·ai
Thomas_YXQ34 分钟前
Unity3D Overdraw性能优化详解
开发语言·人工智能·性能优化·unity3d
lanbing41 分钟前
PHP 与 面向对象编程(OOP)
开发语言·php·面向对象
yzx99101342 分钟前
Gensim 是一个专为 Python 设计的开源库
开发语言·python·开源
麻雀无能为力1 小时前
python自学笔记2 数据类型
开发语言·笔记·python
Ndmzi1 小时前
matlab与python问题解析
python·matlab
懒大王爱吃狼1 小时前
怎么使用python进行PostgreSQL 数据库连接?
数据库·python·postgresql
猫猫村晨总1 小时前
网络爬虫学习之httpx的使用
爬虫·python·httpx