Search code examples
pythondictionarypolynomials

Pretty printing polynomials with dictionary python


I'm struggling to create the __ str __ function (aka pretty print) with polynomials, where dictionaries are used to contain the powers as keys and the elements as coefficients. I have done it with lists but I haven't mastered dictionaries yet. Is there anything to improve?

You can see in the second polynomial that if my last constant is not a constant, after arranging the keys with the reverse() function, the plus is always there, what can i do to prevent that? By the way I am trying to overload operators, after I've done this I'll try to do __ add__, __ mul__, __ sub__, and __ call__... though I would finish this one first :P

class Polynomial(object):                                
  def __init__(self, coefficients):
    self.coefficients = coefficients

  def __str__(self):
     polyd = self.coefficients
     exponent = polyd.keys()  
     exponent.reverse()          
     polytostring = ' '
     for i in exponent:
        exponent = i
        coefficient = polyd[i]
        if i == 0:
            polytostring += '%s' % coefficient
            break
        polytostring += '%sx^%s + ' % (coefficient, exponent)


     return polytostring


dict1 = {0:1,1:-1}
p1 = Polynomial(dict1)

dict2 = {1:1,4:-6,5:-1, 3:2}
p2 = Polynomial(dict2)

print p1
print p2

Solution

    1. Remove break statement because for loop will end(break) when exponent value is equal to 0.

    code:

    class Polynomial(object):                                
        def __init__(self, coefficients):
            self.coefficients = coefficients
    
        def __str__(self):
            polytostring = ' '
            for exponent, coefficient in self.coefficients.iteritems():
                if exponent == 0:
                    polytostring += '%s + ' % coefficient
                else:
                    polytostring += '%sx^%s + ' % (coefficient, exponent)
    
            polytostring = polytostring.strip(" + ")
    
            return polytostring
    
    
    dict1 = {0:1, 1:-1}
    p1 = Polynomial(dict1)
    
    dict2 = {1:1, 4:-6, 5:-1, 3:2}
    p2 = Polynomial(dict2)
    
    print "First:-", p1
    print "Second:-", p2
    

    Output:

    $ python poly.py 
    First:- 1 + -1x^1
    Second:- 1x^1 + 2x^3 + -6x^4 + -1x^5