行列式の計算(5)

多項式行列式を計算するために、多項式クラスを作ってみた。
こんな風に使う。


f = Poly([1, 2, 0, 3])
g = Poly([1, -2])
print(f)
print(g)
print(f + g)
print(-g)



class Poly(list):
def __add__(self, a):
res = Poly([])
m = len(self)
if isinstance(a, Poly):
n = len(a)
if m < n:
res[0:n] = a[0:n]
for i in range(m):
res[i] += self[i]
else:
res[0:m] = self[0:m]
for i in range(n):
res[i] += a[i]
else:
res[0:m] = self[0:m]
if len(res) == 0:
res.append(a)
else:
res[0] += a
res.normalize()
return res

def __radd__(self, a):
return self + a

def __sub__(self, a):
res = Poly([])
m = len(self)
if isinstance(a, Poly):
n = len(a)
if m < n:
res[0:n] = [ -x for x in a[0:n] ]
for i in range(m):
res[i] -= self[i]
else:
res[0:m] = self[0:m]
for i in range(n):
res[i] -= a[i]
else:
res[0:m] = self[0:m]
if len(res) == 0:
res.append(-a)
else:
res[0] -= a
res.normalize()
return res

def __rsub__(self, a):
return -self + a

def __mul__(self, a):
print(a)
if isinstance(a, Poly):
m = len(self)
n = len(a)
res = Poly([ 0 for i in range(m + n - 1) ])
for i in range(m):
for j in range(n):
res[i+j] += self[i] * a[j]
return res
else:
return Poly([ x * a for x in self ])

def __rmul__(self, a):
return self * a

def __div__(self, a):
m = len(self)
n = len(a)
res = Poly([ 0 for i in range(m - n + 1) ])
b = Poly([ x for x in self ])
for i in range(m - n, -1, -1):
d = b[i+n-1] / a[n-1]
for j in range(n):
b[i+j] -= d * a[j]
res[i] = d

return res

def __neg__(self):
return Poly([ -x for x in self ])

def normalize(self):
for i in range(len(self) - 1, -1, -1):
if self[i] == 0:
self[i:] = [ ]
else:
return

def __str__(self):
s = ""
n = len(self)
if n == 0:
s = "0"
else:
for i in range(0, n):
if self[i] == 0:
continue
if i == 0:
s = str(self[i])
else:
tmp = ""
if self[i] == 1:
pass
elif self[i] == -1:
tmp = "-"
else:
tmp = str(self[i])
if s != "" and self[i] > 0:
tmp = "+" + tmp
tmp += "x"
if i > 1:
tmp += "^" + str(i)
s += tmp
return s