I am making a class of polynomial objects represented by dictionaries:
3 * x ^ 2 + x + 2 == {2: 3, 1: 1, 0: 2}
This is the part of my code relevant to the question:
class Sparse_polynomial():
def __init__(self, coeffs_dict):
self.coeffs_dict = coeffs_dict
def __repr__(self):
terms = [" + ("+str(self.coeffs_dict[k])+"*x^" + str(k)+")" \
for k in sorted(self.coeffs_dict.keys(), reverse=True)]
terms = "".join(terms)
return terms[3:]
def __neg__(self):
neg_pol= self.coeffs_dict
for key in self.coeffs_dict:
neg_pol[key]= -self.coeffs_dict[key]
return Sparse_polynomial(neg_pol)
Whenever I try to use a method __neg__, the original object changes. For instance:
>>> p1= Sparse_polynomial({1:3,5:1})
>>> p1
(1*x^5) + (3*x^1)
>>> -p1
(-1*x^5) + (-3*x^1)
>>> p1
(-1*x^5) + (-3*x^1)
>>>
I really can't understand why the original one is changing p1. I did not make any direct changes to it, only access to its fields.
Can anyone clarify so that I can fix this?
source
share