Add polynomial subtraction

This commit is contained in:
Varmen8 2018-06-27 23:04:58 +02:00
parent 437428d6aa
commit 6454c537c2

63
main.py
View File

@ -33,8 +33,7 @@ class Poly:
def __mul__(self, other):
if self.int_mod != other.int_mod:
raise Exception("Different modulo")
assert self.int_mod == other.int_mod
elements = {}
@ -63,8 +62,7 @@ class Poly:
def __add__(self, other):
if self.int_mod != other.int_mod:
raise Exception("Different modulo")
assert self.int_mod == other.int_mod
elements = self.elements.copy()
@ -74,8 +72,29 @@ class Poly:
else:
elements[f] = other.elements[f]
return Poly(self.int_mod,
list(reversed(list(sorted(elements.values())))))
els = {}
for i in reversed(range(len(elements))):
els[f"x{i}"] = elements[f"x{i}"]
return Poly(self.int_mod, list(reversed(list(els.values()))))
def __sub__(self, other):
assert self.int_mod == other.int_mod
elements = self.elements.copy()
for e in other.elements:
if e in elements:
elements[e] -= other.elements[e]
else:
elements[e] = -other.elements[e]
els = {}
for i in reversed(range(len(elements))):
els[f"x{i}"] = elements[f"x{i}"]
return Poly(self.int_mod, list(reversed(list(els.values()))))
def __truediv__(self, other):
@ -134,24 +153,36 @@ if __name__ == "__main__":
# print(c.elements)
# print(c)
# print(p ** 2)
d = Poly(5, [-3, 1])
# print(p)
# print(d)
# print(p)
# print(p + d)
d = Poly(5, [-3, 1])
g = Poly(5, [1, 2, 1])
print(d)
print(g)
print()
# print()
# print(g ** 2)
print(d)
print(g)
# c = d * g
print(g * d)
print(d * g)
print(g + d)
# print(d)
# print(g)
# # c = d * g
# print(g * d)
# print(d * g)
# print(g + d)
# print(d + g)
# print(d)
# print(g)
print(g - d)
print(d - g)
print()
print(d + g)
print(d)
print(g)
print(g + d)
# print(d)
# print(g)
# print(g - d)
# print(p / d)
# print(p.elements[0])