【发布时间】:2011-06-22 06:48:28
【问题描述】:
嗨,
我试图找到一个通用表达式来获得 order 和 n_variables 阶的多元多项式的指数,就像等式 (3) 中的 reference 中呈现的那样。
这是我当前的代码,它使用 itertools.product 生成器。
def generalized_taylor_expansion_exponents( order, n_variables ):
"""
Find the exponents of a multivariate polynomial expression of order
`order` and `n_variable` number of variables.
"""
exps = (p for p in itertools.product(range(order+1), repeat=n_variables) if sum(p) <= order)
# discard the first element, which is all zeros..
exps.next()
return exps
想要的输出是这样的:
for i in generalized_taylor_expansion_exponents(order=3, n_variables=3):
print i
(0, 0, 1)
(0, 0, 2)
(0, 0, 3)
(0, 1, 0)
(0, 1, 1)
(0, 1, 2)
(0, 2, 0)
(0, 2, 1)
(0, 3, 0)
(1, 0, 0)
(1, 0, 1)
(1, 0, 2)
(1, 1, 0)
(1, 1, 1)
(1, 2, 0)
(2, 0, 0)
(2, 0, 1)
(2, 1, 0)
(3, 0, 0)
实际上这段代码执行得很快,因为只创建了生成器对象。如果我想用这个生成器中的值填充一个列表,执行真的开始变慢了,主要是因为对sum 的大量调用。 order 和 n_variables 的典型值分别为 5 和 10。
如何显着提高执行速度?
感谢您的帮助。
大卫烤宽面条
【问题讨论】:
-
我不太了解你想要做什么的细节,但你有没有在 numpy 中查看是否有任何功能可以帮助你?
标签: python optimization generator itertools