我目前正在使用Python中的Project Euler问题53。解决方案非常简单,但涉及以下列表理解:
[scipy.misc.comb(n, r, exact=True)
for n in range(1,maxn+1)
for r in range(0,n+1)
if scipy.misc.comb(n, r, exact=True) > threshold]
我关心的是scipy.misc.comb()函数每次迭代都会被调用两次。有没有办法用某种参考替换它的一个或另一个出现;或者是解释器足够智能,以便意识到这两个实例将评估相同的东西?
答案 0 :(得分:6)
您可以将scipy.misc.comb()
函数放入生成器表达式中:
[comb for comb in
(scipy.misc.comb(n, r, exact=True)
for n in range(1,maxn+1) for r in range(0,n+1))
if comb > threshold]
并且每次迭代都会在生成器上计算一次。
将生成器表达式放入单独的变量可能会更清楚:
calculated = (scipy.misc.comb(n, r, exact=True)
for n in range(1,maxn+1) for r in range(0,n+1))
[comb for comb in calculated if comb > threshold]
将此视为传送带; calculated
生成器只生成其输出,因为列表推导会迭代它。