Class polynomial - list assignment index out of range

0

I'm not sure how to do this, but I'm not sure how to do this.

  

File "/home/leticia/Documentos/python/Poo/polinomio.py", line 30, in          p3 = p1 + p2 File "/home/leticia/Documentos/python/Poo/polinomio.py", line 19, in    add       indexError: list assignment index out of range

In these attempts to solve, I've even added an attribute to pass the vector dimension, but I'm still in it, where am I going wrong?

class Polinomio:

    def __init__ (self, termos = None, n = 0):
        self.termos = termos or []
        self.n = [0] * n

    def __len__ (self):
        return len(self.termos)

    def __setitem__ (self, i, x):
        self.termos[i] = x

    def __getitem__(self, i):
        return self.termos[i] 

    def __add__ (self, other):
        soma = Polinomio(n = self.termos.__len__())
        for i in range(self.termos.__len__()):
            soma.termos[i] = self.termos[i] + other[i]
        return soma

    def print (self):
        print(self.termos)


p1 = Polinomio([1, 2, 3])
p2 = Polinomio([1, 2, 3])
p2.print()
p3 = Polinomio()
p3 = p1 + p2
    
asked by anonymous 31.08.2017 / 18:44

1 answer

1

[TL; DR]

Try this:

class Polinomio:

    def __init__ (self, termos = None, n = 0):
        self.termos = termos or []
        self.n = [0] * n

    def __len__ (self):
        return len(self.termos)

    def __setitem__ (self, i, x):
        self.termos[i] = x

    def __getitem__(self, i):
        return self.termos[i] 

    def __add__ (self, other):            
        return [x + y for x, y in zip(self.termos, other.termos)]

    def print (self):
        print(self.termos)

Testing:

p1 = Polinomio([1, 2, 3])
p2 = Polinomio([4, 5, 6])
print ('Termos de p1: ', p1.termos)
print ('Termos de p2: ', p2.termos)
print ('Soma de p1+p2: ', p1+p2)

Termos de p1:  [1, 2, 3]
Termos de p2:  [4, 5, 6]
Soma de p1+p2:  [5, 7, 9]

See working at repl.it.

    
31.08.2017 / 19:30