python - 如何获得 0 作为我的斐波那契序列的第一项?
问题描述
当输入为 0 时,我不知道如何将 0 显示为斐波那契数列函数的输出。如何使用 while 循环来执行此操作?
def Fibonacci(n):
i= 0
present = 1
previous = 0
while i <= n:
nextterm = present + previous
present = previous
previous = nextterm
i += 1
return nextterm
I expect the output of Fibonacci(0) to be 0
解决方案
您当前的代码可以通过返回present
而不是nextterm
.
如果你很好奇,Python 中常见的 Fibonacci 实现通常如下所示。这个版本中的变量命名对我来说似乎更直观一些。
def fib(n):
cur, nxt = (0, 1)
while n > 0:
cur, nxt = (nxt, cur + nxt)
n -= 1
return cur
推荐阅读
- php - 我的 PHP 表单发送数据但 sql 显示所有列零记录
- android - 在主线程外运行时对 Cloud Firestore 进行同步调用
- c# - 替换方法不适用于 C# 中的转义字符 '\xA0'
- javascript - 如何获取密钥并将其附加到 json 文件中的下一个值?
- python - 为多处理序列化对象很慢——有没有办法只序列化一次?
- python - Cloud Foundry 上的 Flask 应用程序 - 命令“python setup.py egg_info”失败,错误代码为 1
- python - Flask App 拒绝连接
- elasticsearch - 范围过滤器不适用于“gt”运算符但适用于“lt”
- routing - 骆驼的轻型工作流程
- node.js - Namecheap 共享主机和多节点 JS 应用程序