Python:这个斐波那契函数有什么问题?
我尝试编写一个简单的 python 函数,该函数应返回不超过指定最大值的 fib 数字列表。但我收到这个错误。我似乎无法找出我做错了什么。
def fib(a,b,n):
f = a+b
if (f > n):
return []
return [f].extend(fib(b,f,n))
>>>fib(0,1,10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lvl2.py", line 35, in fib
return [f].extend(fib(b,f,n))
File "lvl2.py", line 35, in fib
return [f].extend(fib(b,f,n))
File "lvl2.py", line 35, in fib
return [f].extend(fib(b,f,n))
File "lvl2.py", line 35, in fib
return [f].extend(fib(b,f,n))
TypeError: 'NoneType' object is not iterable
I tried to write a simple python function which should return the list of fib numbers upto some specified max. But I am getting this error. I can't seem to find out what I am doing wrong.
def fib(a,b,n):
f = a+b
if (f > n):
return []
return [f].extend(fib(b,f,n))
>>>fib(0,1,10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "lvl2.py", line 35, in fib
return [f].extend(fib(b,f,n))
File "lvl2.py", line 35, in fib
return [f].extend(fib(b,f,n))
File "lvl2.py", line 35, in fib
return [f].extend(fib(b,f,n))
File "lvl2.py", line 35, in fib
return [f].extend(fib(b,f,n))
TypeError: 'NoneType' object is not iterable
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
list.extend
就地扩展列表。您可以使用+
运算符将两个列表连接在一起。但是,您的代码并不是特别Pythonic。您应该使用无限序列生成器,或者作为对代码的轻微改进:
使用无限序列生成器的示例:
您可以使用
fibgen()
创建生成器,并使用以下方法获取下一个值:.next()
。list.extend
extends a list in-place. You can use the+
operator to concatenate two lists together.However, your code isn't particularly Pythonic. You should use a generator for infinite sequences, or, as a slight improvement over your code:
An example using generators for infinite sequences:
You can create the generator with
fibgen()
and pull off the next value using.next()
.您可能对一个特别简洁的 Fibonacci 实现感兴趣,尽管它仅适用于 Python 3.2 及更高版本:
第一行的要点是记住递归调用。换句话说,例如
fib(20)
的计算速度很慢,因为您将重复大量工作,因此我们在计算值时缓存它们。如上所述,这样做可能仍然更有效
,因为它没有大缓存的空间开销。
You may be interested in an especially neat Fibonacci implementation, though it only works in Python 3.2 and higher:
The point of the first line is to memoise the recursive call. In other words, it is slow to evaluate e.g.
fib(20)
, because you will repeat a lot of effort, so instead we cache the values as they are computed.It is still probably more efficient to do
as above, because it doesn't have the space overhead of the large cache.