使用单个系数对python进行加法和乘法

时间:2016-08-23 07:55:39

标签: python python-3.x

我想使用python添加和乘法多项式。 例如,如果问题是:

platforms/android/bin/hellocordova-debug.apk

我的代码:

addpoly([(4,3),(3,0)],[(-4,3),(2,1)])
[(2, 1),(3, 0)] (answer)

我的输出

def addpoly( x, y):
 min_len = min( len(x), len(y))
 return x[: -min_len] + y[: -min_len] + [ x[i] + y[i] for i in range(-min_len,0)  

必需输出:

addpoly([(4,3),(3,0)],[(-4,3),(2,1)])
[(4, 3, -4, 3), (3, 0, 2, 1)]

如果可能,我想收到任何建议。 谢谢。

1 个答案:

答案 0 :(得分:0)

最简单的方法是将多项式转换为带有dict项的power -> coefficient

In [1]: p1 = [(4,3),(3,0)]

In [2]: p2 = [(-4,3),(2,1)]

In [3]: from collections import Counter

In [4]: p1_c = Counter(dict((degree, coef) for (coef, degree) in p1))

In [5]: p2_c = Counter(dict((degree, coef) for (coef, degree) in p2))

In [6]: p1_c, p2_c
Out[6]: (Counter({0: 3, 3: 4}), Counter({1: 2, 3: -4}))

然后你可以添加这些词典:

In [7]: p1_c + p2_c
Out[7]: Counter({0: 3, 1: 2})

将它们转换回列表:

In [8]: [(c, d) for (d, c) in (p1_c + p2_c).items()]
Out[8]: [(3, 0), (2, 1)]

您也可以按度数对其进行排序(以符合您的预期输出)

In [9]: from operator import itemgetter

In [10]: sorted(((c, d) for (d, c) in (p1_c + p2_c).items()), key=itemgetter(1), reverse=True)
Out[10]: [(2, 1), (3, 0)]

您也可以找到有用的sympy库,它允许您以非常简洁的方式处理符号表达式(即使用多项式)。