3 回答
TA贡献1777条经验 获得超3个赞
还是另一种方式。使用 itertools groupby 组合相似的术语:
from itertools import groupby
def multipoly(poly1,poly2):
#multiply two polynolials
temp = [(p1[0]*p2[0], p1[1]+p2[1]) for p1 in poly1 for p2 in poly2]
#sort to use for groupby
temp = sorted(temp, key= lambda x: x[1])
#groupby second term
g = groupby(temp, lambda x: x[1])
#combine terms
result = []
for k,v in g:
result.append((sum([i[0] for i in v]), k))
result.sort(key=lambda x: -x[1])
return result
TA贡献1784条经验 获得超8个赞
如果你只是想一个函数来乘两个多项式,表示为元组的列表[(coef, expn) ...],你可以通过长期的两个多项式乘法任期开始p1, p2喜欢这个
p3 = [(c1*c2, e1+e2) for c1, e1 in p1 for c2, e2 in p2]
但是你有一个问题,因为一般来说,你会有多个具有相同指数的术语,我们可以使用字典来规范化结果p3
d = {}
for c, e in p3:
d[e] = d.get(e, 0) + c
注意,d.get(e, 0)返回d[e]如果指数中已经存在d或返回0。
最后,您希望将结果作为元组列表返回
p3 = [(c, e) for e, c in d.items()]
但不能保证此列表按指数递减的顺序排序
p3 = sorted(p3, key=lambda t: -t[1])
可以将所有这些放在一个可调用的
def pmult(p1, p2):
d = {}
for coef, expn in [(c1*c2, e1+e2) for c1, e1 in p1 for c2, e2 in p2]:
d[expn] = d.get(expn,0)+coef
return sorted([(c, e) for e, c in d.items()], key=lambda t: -t[1])
一个测试:
In [25]: a = [(1,2),(3,0)]
In [26]: b = [(1,4),(2,3),(3,2),(4,1),(5,0)]
In [27]: def pmult(p1, p2):
...: d = {}
...: for coef, expn in [(c1*c2, e1+e2) for c1, e1 in p1 for c2, e2 in p2]:
...: d[expn] = d.get(expn,0)+coef
...: return sorted([(c, e) for e, c in d.items()], key=lambda t: -t[1])
In [28]: pmult(a, b)
Out[28]: [(1, 6), (2, 5), (6, 4), (10, 3), (14, 2), (12, 1), (15, 0)]
添加回答
举报