4

やあ、次数の多変量多項式の指数を取得するための一般的な式を見つけようとしてorderますn_variables

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。との典型的な値はordern_variablesそれぞれ 5 と 10 です。

どうすれば実行速度を大幅に改善できますか?

助けてくれてありがとう。

ダヴィデ・ラザニア

4

2 に答える 2

2

実際、パフォーマンスの最大の問題は、生成しているタプルのほとんどが大きすぎて、破棄する必要があることです。以下は、必要なタプルを正確に生成するはずです。

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. 
    """
    pattern = [0] * n_variables
    for current_sum in range(1, order+1):
        pattern[0] = current_sum
        yield tuple(pattern)
        while pattern[-1] < current_sum:
            for i in range(2, n_variables + 1):
                if 0 < pattern[n_variables - i]:
                    pattern[n_variables - i] -= 1
                    if 2 < i:
                        pattern[n_variables - i + 1] = 1 + pattern[-1]
                        pattern[-1] = 0
                    else:
                        pattern[-1] += 1
                    break
            yield tuple(pattern)
        pattern[-1] = 0
于 2011-02-06T16:17:39.907 に答える
0

必要な要素のみを生成するように、再帰的に記述してみます。

def _gtee_helper(order, n_variables):
    if n_variables == 0:
        yield ()
        return
    for i in range(order + 1):
        for result in _gtee_helper(order - i, n_variables - 1):
            yield (i,) + result


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. 
    """
    result = _gtee_helper(order, n_variables)
    result.next() # discard the first element, which is all zeros
    return result
于 2011-02-06T17:12:27.923 に答える