From bc3dcdaabe2971fc0328316e7a898e8a7bf64c55 Mon Sep 17 00:00:00 2001 From: Szymon Wojciechowski Date: Wed, 27 Jun 2018 17:29:48 +0000 Subject: [PATCH] added polynomial addition --- wielomiany.py => poly.py | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) rename wielomiany.py => poly.py (73%) diff --git a/wielomiany.py b/poly.py similarity index 73% rename from wielomiany.py rename to poly.py index 833e9d6..2f335ff 100644 --- a/wielomiany.py +++ b/poly.py @@ -9,6 +9,22 @@ class Polynomial: self.degree = len(coef_list) - 1 self.coefficients = coef_list + @staticmethod + def add(p1, p2): + result = [] + f = p1.coefficients + g = p2.coefficients + if len(f) >= len(g): + result = f + for i in range(0, len(g)): + result[i] = f[i] + g[i] + else: + result = g + for i in range(0, len(f)): + result[i] = f[i] + g[i] + result = [x % int(Polynomial.n) for x in result] + return Polynomial(result) + @staticmethod def multiply(p1, p2): result = [0] * (p1.degree + p2.degree + 1) @@ -17,14 +33,14 @@ class Polynomial: for i in range(0, len(f)): for j in range(0, len(g)): result[i+j] += f[i] * g[j] - result = [x % int(n) for x in result] + result = [x % int(Polynomial.n) for x in result] return Polynomial(result) @staticmethod def divide(p1, p2): def inverse(x): - for i in range(1, int(n)): - r = (i * x) % int(n) + for i in range(1, int(Polynomial.n)): + r = (i * x) % int(Polynomial.n) if r == 1: break else: @@ -41,13 +57,13 @@ class Polynomial: tmp_coef = f_lead_coef * inverse(g_lead_coef) tmp_exp = len(f) - 1 - g_deg tmp = [] - for i in range(tmp_exp): + for _ in range(tmp_exp): tmp.append(0) tmp.append(tmp_coef) tmp_poly = Polynomial(tmp) sub = Polynomial.multiply(p2, tmp_poly) f = [x - y for x, y in zip(f, sub.coefficients)] - f = [x % int(n) for x in f] + f = [x % int(Polynomial.n) for x in f] while f and f[-1] == 0: f.pop() return Polynomial(f) @@ -60,6 +76,7 @@ class Polynomial: def main(): + Polynomial.n = int(sys.argv[1]) c1 = ast.literal_eval(sys.argv[2]) c2 = ast.literal_eval(sys.argv[3]) @@ -86,5 +103,4 @@ def main(): print(ans) if __name__ == "__main__": - n = int(sys.argv[1]) - main() \ No newline at end of file + main()