青春有我
如果你只是想一个函数来乘两个多项式,表示为元组的列表[(coef, expn) ...],你可以通过长期的两个多项式乘法任期开始p1, p2喜欢这个p3 = [(c1*c2, e1+e2) for c1, e1 in p1 for c2, e2 in p2]但是你有一个问题,因为一般来说,你会有多个具有相同指数的术语,我们可以使用字典来规范化结果p3d = {}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)]