Adding and scaling polynomials in python using class -
i'm making polynomial class can't add , scale function work properly.
the scale function should work multiplying coefficients of polynomial given x. example if y=2x^3+4x^2
, x=2
, y=4x^3+8x^2
the add function should add terms of 2 polynomials.
i've added comments code explain how trying functions work
class polynomial: def __init__(self, coefficients): self.coeffs=coefficients def scale(self, x): return polynomial(self.coeffs*x) def add(self, other): #getting highest degree add self.degree=len(self.coeffs)-1 other.degree=len(other.coeffs)-1 maxcoeff=max(self.degree,other.degree)+1 #adding 0's end of shortest 1 make adding easiers (pairwise) self_temp = self.coeffs + [0]*(maxcoeff-self.degree-1) other_temp = other.coeffs + [0]*(maxcoeff-other.degree-1) #adding elementwise coeffs = [self_temp[i] + other_temp[i] in range(len(other_temp))] return polynomial(coeffs)
this not looking for:
def scale(self, x): return polynomial(self.coeffs*x)
with multiplication growing/shrinking list.
because coeffs
iterable. want:
def scale(self, x): return polynomial([c * x c in self.coeffs])
and this:
self_temp = self.coeffs + [0]*(maxcoeff-self.degree-1) other_temp = other.coeffs + [0]*(maxcoeff-other.degree-1) coeffs = [self_temp[i] + other_temp[i] in range(len(other_temp))
can possibly better expressed as:
coeffs = [x + y x, y in itertools.izip_longest(self.coeffs, other.coeffs, fillvalue=0)]
Comments
Post a Comment