dictionary - Multiplying polynomials in Python with the use of dictionaries -
i have written little class initializer takes argument dictionary. following dictionary {2:3, 4:5, 6:7}
translates polynomial 3x^2 + 5x^4 + 7x^6
keys of dictionary exponents , values coefficients.
i have managed implement comparison of 2 polynomials in class using eq method , can add them. here code:
class polynomial(object): def __init__(self, polynom = {}): self.polynom = polynom self.poly_string = self.nicepolynom(polynom) #just method make output nice def __str__(self): return self.poly_string # debugging purposes def coefficient(self, exponent): """ small function returns coefficient of corresponding exponent i.e. if our polynomial p = 3x^9 p.coefficient(9) return 3 """ try: return self.polynom[exponent] except keyerror: pass def __add__(self,other): """ overloading + operator not elegant solution understandable. check first if our exponent present in both polynomials if present in 1 , symmetric case, adding result dictionary add """ add = {} exponent in self.polynom: if exponent in other.polynom: add[exponent] = self.polynom[exponent] + other.polynom[exponent] exponent in self.polynom: if exponent not in other.polynom: add[exponent] = self.polynom[exponent] exponent in other.polynom: if exponent not in self.polynom: add[exponent] = other.polynom[exponent] return add def __mul__(self, other): mult = {} exponent1 in self.polynom: exponent2 in other.polynom: mult[exponent1 + exponent2] = self.coefficient(exponent1) * other.coefficient(exponent2) return mult
the crucial step , main problem during multiplication want make use of addition. absolutely new oop , don't see how can initialize polynom object on can perform addition arithmetic.
if multiply polynomial @ moment getting correct exponents, besides initial , end term, coefficients way off.
here's 1 approach might work:
for exponent1 in self.polynom: exponent2 in other.polynom: this_exponent = exponent1 + exponent2 this_coeff = self.coefficient(exponent1) * other.coefficient(exponent2) try: mult[this_exponent] += this_coeff except keyerror: mult[this_exponent] = this_coeff
that is, update coefficient of new power, , catch exception raised first time power encountered initialize dictionary @ corresponding exponent key. (this more "pythonic" if..else
clause if care such things).
Comments
Post a Comment