斐波那契数列

斐波那契数列: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
相关推荐
阿尔的代码屋18 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者1 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时2 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿2 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng83 天前
Python+Django+H5+MySQL项目搭建
python·django