<p>作为<a href="https://stackoverflow.com/questions/39057546/how-to-calculate-sum-of-two-polynomials#comment65466242_39057546">comments</a>中的<a href="https://stackoverflow.com/questions/39057546/how-to-calculate-sum-of-two-polynomials#comment65465088_39057546">suggested</a>,将多项式表示为指数的<a href="https://en.wikipedia.org/wiki/Multiset" rel="nofollow noreferrer">multisets</a>要简单得多。</p>
<p>在Python中,最接近multiset的是<a href="https://docs.python.org/3/library/collections.html#collections.Counter" rel="nofollow noreferrer">Counter</a>数据结构。使用将指数映射到系数的<code>Counter</code>(甚至只是一个普通字典)将自动合并具有相同指数的条目,正如您在编写简化多项式时所期望的那样。</p>
<p>您可以使用<code>Counter</code>执行操作,然后在使用完以下函数后转换回成对列表表示:</p>
<pre><code>def counter_to_poly(c):
p = [(coeff, exp) for exp, coeff in c.items() if coeff != 0]
# sort by exponents in descending order
p.sort(key = lambda pair: pair[1], reverse = True)
return p
</code></pre>
<p>若要添加多项式,可以像指数一样分组并求其系数之和。</p>
<pre><code>def addpoly(p, q):
r = collections.Counter()
for coeff, exp in (p + q):
r[exp] += coeff
return counter_to_poly(r)
</code></pre>
<p>(事实上,如果您始终坚持使用计数器表示,您只需<code>return p + q</code>)。</p>
<p>若要乘法多项式,请将一个多项式中的每个项与另一个多项式中的每个项配对相乘。而且,要乘项,你可以加上指数和乘系数。</p>
<pre><code>def mulpoly(p, q):
r = collections.Counter()
for (c1, e1), (c2, e2) in itertools.product(p, q):
r[e1 + e2] += c1 * c2
return counter_to_poly(r)
</code></pre>