2012-07-02 70 views
-3

我试图让一种可以打印x的n阶多项式函数多项式,Y产生蟒蛇

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?

+2

您的问题被写入的方式,它像“请做我的家庭作业”。你应该真的考虑发布你到目前为止尝试过的东西 – inspectorG4dget

+1

两个变量的多项式需要一个二维的系数矩阵(n x n)。 – Kos

+0

想法:查找帕斯卡的三角形,以及它与多项式展开的关系。 –

回答

2

你可以尝试从什么开始喜欢

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,如果要抑制不需要的输出。

1

既然你想与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,等...)

只是为了笑

+0

我笑了起来 –

0

稍微更广义的:

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)"