Each term of the polynomial can be represented as a pair of integers (coefficient,exponent)
def addpoly(p1,p2): p1=p1+p2 d=dict(p1) dvalue=list(set(d.values())) dkey=list(d.keys()) result={} for n in dvalue: result[n] = 0 for m in dkey: if n == d[m]: result[n] = result[n] + m rkey=list(result.keys()) for i in rkey: if result[i]==0: del result[i] coff=sorted(list(result.keys())) coff.reverse() ans=[(result[k],k) for k in coff] return(ans)
this program is giving correct output, except rest of few cases
For this call addpoly([(1,1),(-1,0)],[(1,2),(1,1),(1,0)])
does not give correct answer, it output []
instead of [(1,2),(2,1)]
. What I reason for this when I convert p1+p2
to dictionary it removes same key items like-- p1+p2=[(1,1),(-1,0),(1,2),(1,1),(1,0)]
dict(p1+p2)
gives {-1:0,1:0}
.