If you simply want a function to multiply two polynomials, represented as a list of tuples [(coef, expn) ...]
you can start by multiplying term by term the two polynomials p1, p2
like this
p3 = [(c1*c2, e1+e2) for c1, e1 in p1 for c2, e2 in p2]
but you have a problem because, in general, you will have more than one term with the same exponent, to normalize the result in p3
we can use a dictionary
d = {}
for c, e in p3:
d[e] = d.get(e, 0) + c
note that d.get(e, 0)
returns d[e]
if the exponent is already present in d
or returns 0
.
Finally, you want back your results as a list of tuples
p3 = [(c, e) for e, c in d.items()]
but this list is not guaranteed to be sorted in order of decreasing exponent
p3 = sorted(p3, key=lambda t: -t[1])
It is possible to put all this in a single callable
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])
A test:
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)]