无限产量问题
这是我的简单代码,
class Fibonacci:
@staticmethod
def series():
fprev = 1
fnext = 1
yield fnext
while True:
yield fnext
fprev,fnext = fnext,fprev+fnext
under10 = (i for i in Fibonacci.series() if i<10)
for i in under10 :
print i
这绝对是显而易见的,但是......为什么解释器永远执行块
while True:
yield fnext
fprev,fnext = fnext,fprev+fnext
? 我在生成器中指定,我只想要元素<10
under10 = (i for i in Fibonacci.series() if i<10)
恕我直言,这是一个有点误解 有什么方法可以在不重写“系列”的情况下防止无限执行?
Here is my simple code
class Fibonacci:
@staticmethod
def series():
fprev = 1
fnext = 1
yield fnext
while True:
yield fnext
fprev,fnext = fnext,fprev+fnext
under10 = (i for i in Fibonacci.series() if i<10)
for i in under10 :
print i
It's absolutely obvious, but...WHY interpreter is executing block
while True:
yield fnext
fprev,fnext = fnext,fprev+fnext
Forever?
I specified in generator,that I want only elements<10
under10 = (i for i in Fibonacci.series() if i<10)
IMHO, it's a little bit misunderstanding
Any way to prevent infinite execution without re-writing "series"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解释器如何知道所有未来的数字将<< 10?它必须(以某种方式)知道它正在生成斐波那契数列,或者必须检查整个数列。
第一个它做不到,所以它做第二个。
您可以使用
itertools.takewhile
:How should the interpreter know that all future numbers will be < 10? It would have to either know (somehow) that it’s churning out the Fibonacci series, or it would have to inspect the whole series.
It can’t do the first, so it does the second.
You can fix this by using
itertools.takewhile
:会继续下去,只是不会产生大于 10 的值。没有任何东西指示 for 循环停止。
你可能会更幸运地做这样的事情:
编辑:
我更喜欢 Konrad 的 itertools 示例,我总是忘记 itertools
Will keep going, it just won't yield values greater than 10. There's nothing instructing the for loop to stop.
You would probably have better luck doing something like:
EDIT:
I like Konrad's itertools example much more, I always forget about itertools
无限循环不是
Fibonacci.series()
方法中的while True:
的结果。这是由under10 = (i for i in Fibonacci.series() if i<10)
生成器引起的,该生成器一直持续运行,因为它没有意识到生成的值永远不会变小。这是同时修复它并概括它的[另一种]方法 - 无需重写series()
- 使用itertools.takewhile()
迭代器:顺便说一句: 您可以稍微简化
Fibonacci.series()
方法,将其更改为产生相同值的方法:The infinite loop isn't a result of the
while True:
in theFibonacci.series()
method. It's caused by theunder10 = (i for i in Fibonacci.series() if i<10)
generator which just keeps going since it doesn't realize the values yielded will never get smaller. Here's [another] way to fix it and generalize it at the same time -- without re-writingseries()
-- using theitertools.takewhile()
iterator:BTW: You can simplify the
Fibonacci.series()
method slightly by changing it to this which yields the same values: