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?

## All 4 Replies

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)``````

hm, your class can't represent `2x^3 + 2x^5` . There must be something wrong...

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.