Spaced
Spaced

Reputation: 231

Multiplying polynomials in Python with the use of dictionaries

I have written a little class which initializer that takes as argument a dictionary. The following dictionary {2:3, 4:5, 6:7} translates to the polynomial 3x^2 + 5x^4 + 7x^6 so the keys of my dictionary are the exponents and its values are the coefficients.

I have successfully managed to implement a comparison of two polynomials in my class using the eq method and I can add them. Here is my code:

class Polynomial(object):
def __init__(self, polynom = {}):
    self.polynom = polynom
    self.poly_string = self.nicePolynom(polynom) #just a method that will make my output look nice

def __str__(self):
    return self.poly_string # for debugging purposes

def coefficient(self, exponent):
    """
    A small function that returns the coefficient of the corresponding exponent

    i.e. if our Polynomial is P = 3x^9 then p.coefficient(9) return 3
    """
    try:
        return self.polynom[exponent]
    except KeyError:
        pass

 def __add__(self,other):
    """
    Overloading the + operator

    Not the most elegant solution but easily understandable. 
    We check first if our exponent is present in both polynomials
    then if its only present in one and the symmetric case, adding the result
    to the dictionary add
    """
    add = {}

    for exponent in self.polynom:
        if exponent in other.polynom:
            add[exponent] = self.polynom[exponent] + other.polynom[exponent]

    for exponent in self.polynom:
        if exponent not in other.polynom:
            add[exponent] = self.polynom[exponent]

    for exponent in other.polynom:
        if exponent not in self.polynom:
            add[exponent] = other.polynom[exponent]
    return add

def __mul__(self, other):

    mult = {}

    for exponent1 in self.polynom:
        for exponent2 in other.polynom:
            mult[exponent1 + exponent2] = self.coefficient(exponent1) * other.coefficient(exponent2)

    return mult

The crucial step and my main problem is that during the multiplication I want to make use of the addition. But I am absolutely new to OOP and I don't see how I can initialize a Polynom object now on which I can perform the addition arithmetic.

If I multiply a polynomial by itself at the moment I am getting the correct exponents, but besides the initial and the end term, all the coefficients are way off.

Upvotes: 0

Views: 1532

Answers (1)

xnx
xnx

Reputation: 25518

Here's one approach that might work:

for exponent1 in self.polynom:
    for 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 the coefficient of the new power, and catch the Exception that is raised the first time a power is encountered to initialize the dictionary at the corresponding exponent key. (This is more "Pythonic" that an if..else clause if you care about such things).

Upvotes: 2

Related Questions