0

Hey all, I'm trying to write a Polynomial Class but I'm having some trouble. I'm having the coefficients and exponents stored in a dictionary, like so...

class Polynomial:
    def __init__(self, *termpairs):
        self.termdict = dict(termpairs)
        print (self.termdict)

if __name__ == '__main__':
    d1 = Polynomial((2,3), (4,5), (8,9))
    print (d1)

This will give me...

{8: 9, 2: 3, 4: 5}

Now I want to also have an __str__ method, however, I'm not quite sure how to represent this as a string. Polynomial((2,3), (4,5), (8,9)) as a string should look like:
2x^3 + 4x^5 + 8x^9

Anyone have any tips?

5
Contributors
4
Replies
8
Views
5 Years
Discussion Span
Last Post by pyTony
0

A hint regarding accessing the dictionary.

class Polynomial:
    def __init__(self, *termpairs):
        self.termdict = dict(termpairs)
        print (self.termdict)
 
    def print_result(self, key):
        print "%dx^%d" % (key, self.termdict[key])

if __name__ == '__main__':
    d1 = Polynomial((2,3), (4,5), (8,9))
    ## extract and sort keys to process in numerical order
    keys=d1.termdict.keys()
    keys.sort()
    for key in keys:
        d1.print_result(key)

Edited by woooee: n/a

0

I would be tempted to represent the polynomial as a list of coefficients. The nth item in the list is the coefficient of x^n This requires specific 0 coefficients for all terms. It doesn't work (without jiggering) for negative exponents.

A dict also works: Key is exponent, value is coefficient. You walk through them with

for exponent in sorted(poly_dict.keys())
    # do something per term

The use of sorted makes sure you see the terms in the expected order, and you don't have to specify the 0 coefficients so it is nice for 'sparse' polynomials. Works for negative exponents too.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.