-2

I want to overload my string method, s.t. I get the following output:

print Class_name({6:7, 4:5, 7:7}) 
7*x^7 + 7*x^6 + 5*x^4

I did the following:

def __str__(self):
    self.poly = []
    for k,v in sorted(self.dictionary.iteritems()):
        if k == 0:
            self.poly.append(str(v))
        elif v == 1:
            self.poly.append('*x^'+str(k))
        else:
            self.poly.append(str(v)+'*x^'+str(k))
    out = ""
    for el in self.poly:
        out += str(el) + " + "
    self.out = out[:-2]
    return self.out

Why does this not work? Entering print Class_name({6:7, 4:5, 7:7}) , I get

{4: 13, 6: 14, 7: 7}

Thanks for any help!

Edit: If I've an additional def:

def __add__(self, other):
    out = self.dictionary
    for k,v in sorted(other.dictionary.iteritems(), reverse=True):
        try:
            out[k] += v
        except:
            out[k] = v

    return out

and I want to do this:

print Class_name({6:7, 4:5, 7:7})+Class_name({6:7, 4:5, 7:7})

I get: {6:14, 4:10, 7:14} instead of the desired representation.

DMan
  • 61
  • 2
  • 10

3 Answers3

1

This works for me (cut and paste from your code, wrapped in a class definition)

class cn:

    def __init__(self, d):
        self.dictionary = d

    def __str__(self):
        self.poly = []
        for k,v in sorted(self.dictionary.iteritems()):
            if k == 0:
                self.poly.append(str(v))
            elif v == 1:
                self.poly.append('*x^'+str(k))
            else:
                self.poly.append(str(v)+'*x^'+str(k))
        out = ""
        for el in self.poly:
            out += str(el) + " + "
        self.out = out[:-2]
        return self.out


print cn({"1":"2"})


~ mgregory$ python foo.py
2*x^1 
~ mgregory$ python --version
Python 2.7.5
~ mgregory$ 

I wonder whether you didn't actually define the __str__() of your class - maybe you just defined a function called __str__()...

GreenAsJade
  • 14,459
  • 11
  • 63
  • 98
1

For the addition to work:

def __add__(self, other):

    #...

    return Class_name(out)
jean-loup
  • 580
  • 4
  • 17
0

You need to define your __repr__ function for the class

class Poly():
    def __init__(self, coeffs):
        values = [(factor, power) for power, factor in coeffs.items()]
        self.poly = sorted(values, reverse = True)

    def __repr__(self):
        return ' + '.join('{}*x^{}'.format(f, p) for f, p in self.poly)

Example

>>> a = Poly({6:7, 4:5, 7:7})

>>> a
7*x^7 + 7*x^6 + 5*x^4

>>> print(a)
7*x^7 + 7*x^6 + 5*x^4

>>> str(a)
'7*x^7 + 7*x^6 + 5*x^4'
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218