I am quite new to programming, Python and object-oriented programming in general. For a school assignment, I had to write a code that defines a "polynomial" class and, with this, find the root of a polynomial. As the code did not behave as expected, I started analysing it and realised that a global variable, namely the list of coefficients representing the polynomial, which is the "input" for the polynomial class, was being modified. The problem is that I just can't seem to figure out what (part of the code) is causing this manipulation. Below is (the relevant part of) the code I use:
#set input list
il=[1,1,-1]
#define B!/(O-1)!, note that O is an "oh":
def pr(O,B):
p=1
for i in range(O,B+1):
p*=i
return p
#polynomial
class pol:
#init:
def __init__(self,L=[0]):
self.l=L
self.d=len(L)
self.n=self.d-1
#evaluate:
def ev(self,X=0):
if X==0:
return self.l[0]
else:
s=self.l[0]
for i in range(1,self.d):
s+=self.l[i]*X**i
return s
#N-th derivative:
def der(self,N=1):
if self.n < N:
return pol([0])
else:
lwork=self.l
for i in range(N,self.d):
lwork[i]*=pr(i-N+1,i)
return pol(lwork[N:])
#define specific polynomial and take derivative:
#---here I have put some extra prints to make clear what the problem is---
f=pol(il)
print(il)
fd=f.der()
print(il)
fd2=f.der(2)
print(il)
Now this should evaluate to (at least it does so on my machine)
[1,1,-1]
[1,1,-2]
[1,1,-4]
while I expect it to be just the first list three times, since in the definition of the method "der", I do not manipulate the input list, or so it seems to me.
Can someone explain what's going on? Am I missing a (simple) detail, or am I misusing (some aspect of) classes here?
To execute my code, I use an online compiler (repl.it), running on Python 3.5.2.