From 6454c537c2c714b2fcb2d0260bf12e6cf6675d77 Mon Sep 17 00:00:00 2001 From: Varmen8 Date: Wed, 27 Jun 2018 23:04:58 +0200 Subject: [PATCH] Add polynomial subtraction --- main.py | 63 ++++++++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 16 deletions(-) diff --git a/main.py b/main.py index d0f033f..adff4ae 100644 --- a/main.py +++ b/main.py @@ -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])