【发布时间】:2012-03-11 16:05:07
【问题描述】:
Here我找到了一个很好的秘诀,教你如何使用延迟输出的技术来计算数字序列。
我决定用同样的技术来解决Project Euler的第二个问题。
代码:
#Answer: 4613732
from itertools import *
import operator
seeds = [1,2]
def deferred_output():
for i in output:
yield i
result,a1,a2 = tee(deferred_output(),3)
paired = map(operator.add,a1,islice(a2,1,None))
output = chain(seeds,paired)
cropped = takewhile((4000000).__gt__,result)
evened = filter(lambda x: x%2==0,cropped)
print(sum(evened))
代码在 Python 3.x 中完美运行
但是当我尝试在 Python 2.x 中运行它时,出现了以下错误:
Traceback (most recent call last):
File "C:\Documents and Settings\Oleg\Мои документы\_Мои документы\_SyncedWithFlashDrive\Программирование\Project Euler\2\1.py", line 14, in <module>
paired = map(operator.add,a1,islice(a2,1,None))
File "C:\Documents and Settings\Oleg\Мои документы\_Мои документы\_SyncedWithFlashDrive\Программирование\Project Euler\2\1.py", line 9, in deferred_output
for i in output:
NameError: global name 'output' is not defined
这意味着延迟输出在 Python 2.x 中不起作用
这是为什么呢?
【问题讨论】:
标签: python python-3.x python-2.x