本文介绍了列表理解与重复计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Python解决Euler问题53.该解决方案非常简单,但是涉及以下列表理解:

I am currently playing about with Project Euler problem 53 in Python. The solution is trivially simple but involved the following list comprehension:

[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()函数每次迭代将被调用两次.有什么方法可以用某种参考代替它的一个或另一个出现;或者,解释器是否足够聪明,以至于意识到两个实例将对同一事物求值?

My concern is though that the scipy.misc.comb() function would be called twice per iteration. Is there any way of replacing one or other occurrence of it with some sort of reference; alternatively is the interpreter smart enough to realise that the two instances will evaluate to the same thing?

推荐答案

您可以将scipy.misc.comb()函数放入生成器表达式中:

You can put the scipy.misc.comb() function into a generator expression:

[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]

,它将在生成器上每次迭代仅计算一次.

and it'll be calculated just once per iteration over the generator.

将生成器表达式放入单独的变量中可以使这一点更加清楚:

Putting the generator expression into a separate variable may make this clearer:

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生成器仅在列表理解对其进行迭代时才生成其输出.

See this as a conveyor belt; the calculated generator is only producing its output as the list comprehension iterates over it.

这篇关于列表理解与重复计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 04:25