斐波那契数的迭代算法

编程入门 行业动态 更新时间:2024-10-22 21:34:43
本文介绍了斐波那契数的迭代算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我对斐波那契数的迭代算法感兴趣,因此我在Wiki上找到了公式...它看起来很直接,所以我在Python中尝试了它...编译没有问题,公式看起来也不错。 ..不确定为什么会给出错误的输出...我执行不正确吗?

I am interested in an iterative algorithm for Fibonacci numbers, so I found the formula on wiki...it looks straight forward so I tried it in Python...it doesn't have a problem compiling and formula looks right...not sure why its giving the wrong output...did I not implement it right ?

def fib (n): if( n == 0): return 0 else: x = 0 y = 1 for i in range(1,n): z = (x + y) x = y y = z return y for i in range(10): print (fib(i))

输出

0 无 1 1 1 1 1 1

0 None 1 1 1 1 1 1

推荐答案

问题是您的返回y 在您的功能循环。因此,在第一次迭代之后,它将已经停止并返回第一个值:1.除非 n 为0时,否则函数将返回 0 本身,并且在 n 为1的情况下,for循环甚至不会迭代一次,并且没有 return 正在执行(因此 None 返回值)。

The problem is that your return y is within the loop of your function. So after the first iteration, it will already stop and return the first value: 1. Except when n is 0, in which case the function is made to return 0 itself, and in case n is 1, when the for loop will not iterate even once, and no return is being execute (hence the None return value).

要解决此问题,只需将返回y 移出循环即可。

To fix this, just move the return y outside of the loop.

以KebertX的示例为例,这是我亲自在Python中制作的解决方案。当然,如果要处理许多斐波那契值,您甚至可能希望将这两种解决方案结合起来并为数字创建缓存。

Following KebertX’s example, here is a solution I would personally make in Python. Of course, if you were to process many Fibonacci values, you might even want to combine those two solutions and create a cache for the numbers.

def f(n): a, b = 0, 1 for i in range(0, n): a, b = b, a + b return a

更多推荐

斐波那契数的迭代算法

本文发布于:2023-11-29 08:35:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645886.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:算法   迭代

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!