例如,3x^4 - 17x^2 - 3x + 5
。多项式的每个项可以表示为一对整数(系数,指数)。即[(3,4),(-17,2), (-3,1), (5,0)]
我们有以下约束来保证每个多项式都有唯一的表示:
为以下操作编写Python函数:
addpoly(p1,p2)
multpoly(p1,p2)
一些例子:
>>> addpoly( [(4,3),(3,0)], [(-4,3),(2,1)] )
[(2, 1),(3, 0)]
说明:(4x^3 + 3) + (-4x^3 + 2x) = 2x + 3
>>> addpoly( [(2,1)], [(-2,1)] )
[]
说明:2x + (-2x) = 0
>>> multpoly( [(1,1),(-1,0)], [(1,2),(1,1),(1,0)] )
[(1, 3),(-1, 0)]
说明:(x - 1) * (x^2 + x + 1) = x^3 - 1
答案 0 :(得分:2)
您想要定义一个函数,该函数接受任意数量的
形式的参数[(4,3),(3,0)], [(-4,3),(2,1)]
使用addpoly
:可以轻松完成 collections.defaultdict
from collections import defaultdict
def addpoly(*polynoms):
result = defaultdict(int)
for polynom in polynoms:
for factor, exponent in polynom:
result[exponent] += factor
return [(coeff, exponent) for exponent, coeff in result.items() if coeff]
In [68]: addpoly([(4,3),(3,0)],[(-4,3),(2,1)])
Out[68]: [(3, 0), (2, 1)]