For instance, 3x^4 - 17x^2 - 3x + 5
. Each term of the polynomial can be represented as a pair of integers (coefficient, exponent). ie [(3,4),(-17,2), (-3,1), (5,0)]
We have the following constraints to guarantee that each polynomial has a unique representation:
Write Python functions for the following operations:
addpoly(p1,p2)
multpoly(p1,p2)
Some examples:
>>> addpoly( [(4,3),(3,0)], [(-4,3),(2,1)] )
[(2, 1),(3, 0)]
Explanation: (4x^3 + 3) + (-4x^3 + 2x) = 2x + 3
>>> addpoly( [(2,1)], [(-2,1)] )
[]
Explanation: 2x + (-2x) = 0
>>> multpoly( [(1,1),(-1,0)], [(1,2),(1,1),(1,0)] )
[(1, 3),(-1, 0)]
Explanation: (x - 1) * (x^2 + x + 1) = x^3 - 1
You want to define a function that takes an arbitrary amount of arguments of the form
[(4,3),(3,0)], [(-4,3),(2,1)]
addpoly
could be done easily with a collections.defaultdict
:
from collections import defaultdict
def addpoly(*polynoms):
result = defaultdict(int)
for polynom in polynoms:
for factor, exponent in polynom:
result[exponent] += factor
return [(coeff, exponent) for exponent, coeff in result.items() if coeff]
In [68]: addpoly([(4,3),(3,0)],[(-4,3),(2,1)])
Out[68]: [(3, 0), (2, 1)]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.