0
Save people, I’m learning classes in python and created one for application with polynomials, but I’m not able to add two distinct polynomials, always appears the following error:
File "/home/Documents/python/Poo/polinomio.py", line 30, in P3 = P1 + P2 File "/home/Leticia/Documents/python/Poo/polinomio.py", line 19, in add sum.terms[i] = self.terms[i] + other[i] Indexerror: list assignment index out of range
In these attempts to solve, I even added an attribute to pass the dimension of the vector, but I remain in it, where I am missing?
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
In the method
init
try to getself.termos = termos or [0]*n
– Woss
Rode thank you if you want to answer the question so I can mark as resolved
– Marcelo de Sousa
You are using the "magic methods", in my opinion lacked an interesting good, for example, instead of doing
p2.print()
doprint(p2)
orprint(p3)
and see what happens. The desirable (or convention) would be that happen the same as what happens when you call the methodprint
, that is, present the terms.– Sidon