-3

x、yの次数nの多項式を出力できる関数を作成しようとしています。

すなわちpoly(x,y,1)出力しますc[0] + c[1]*x + c[2]*y

すなわちpoly(x,y,2)出力しますc[0] + c[1]*x + c[2]*y + c[3]*x**2 + c[4]*y**2 + c[5]*x*y

アイデアをいただけますか?多分itertools?

4

3 に答える 3

3

あなたは次のようなものから始めようとすることができます

def poly(x,y,n):
    counter = 0
    for nc in range(n+1):
        for i in range(nc+1):
            print "c[", counter, "]",
            print " * ", x, "**", i,
            print " * ", y, "**", nc-i,
            print " + ",
            counter += 1

例えば

poly("x", "y", 2)

を生成します

c[ 0 ]  *  x ** 0  *  y ** 0  +  c[ 1 ]  *  x ** 0  *  y ** 1  +  c[ 2 ]  *  x ** 1  *  y ** 0  +  c[ 3 ]  *  x ** 0  *  y ** 2  +  c[ 4 ]  *  x ** 1  *  y ** 1  +  c[ 5 ]  *  x ** 2  *  y ** 0  + 

if不要な出力を抑制したい場合は、 sを組み込みます。

于 2012-07-02T19:24:14.013 に答える
2

itertoolsを使用した機能的なソリューションが必要だったので、ここにワンライナーがあります。

import itertools as itt
from collections import Counter
n = 3
xy = ("x", "y") # list of variables may be extended indefinitely
poly = '+'.join(itt.starmap(lambda u, t: u+"*"+t if t else u, zip(map(lambda v: "C["+str(v)+"]", itt.count()),map(lambda z: "*".join(z), map(lambda x: tuple(map(lambda y: "**".join(map(str, filter(lambda w: w!=1, y))), x)), map(dict.items, (map(Counter, itt.chain.from_iterable(itt.combinations_with_replacement(xy, i) for i in range(n+1))))))))))

それはあなたに与えるでしょう

C[0]+C[1]*x+C[2]*y+C[3]*x**2+C[4]*y*x+C[5]*y**2+C[6]*x**3+C[7]*y*x**2+C[8]*y**2*x+C[9]*y**3

係数の順序がわずかに異なることに注意してください。これは、任意のnだけでなく、任意の数の変数(x、y、zなど)に対しても機能します。

ただ笑いのために

于 2012-07-02T23:58:12.690 に答える
1

もう少し一般化:

from itertools import product

def make_clause(c, vars, pows):
    c = ['c[{}]'.format(c)]
    vp = (['', '{}', '({}**{})'][min(p,2)].format(v,p) for v,p in zip(vars,pows))
    return '*'.join(c + [s for s in vp if s])

def poly(vars, max_power):
    res = (make_clause(c, vars, pows) for c,pows in enumerate(product(*(range(max_power+1) for v in vars))))
    return ' + '.join(res)

その後poly(['x', 'y'], 2)

"c[0] + c[1]*y + c[2]*(y**2) + c[3]*x + c[4]*x*y + c[5]*x*(y**2) + c[6]*(x**2) + c[7]*(x**2)*y + c[8]*(x**2)*(y**2)"
于 2012-07-02T23:59:19.077 に答える