From e58567b2f8da44c381e1ec4fcb23ebf9294a5281 Mon Sep 17 00:00:00 2001 From: Lafrite Date: Sat, 28 Mar 2015 09:09:32 +0100 Subject: [PATCH] change op.add and op.sub for better - management --- pymath/operator.py | 29 ++++++++++++++++++++++++++++- test/test_render.py | 4 ++-- 2 files changed, 30 insertions(+), 3 deletions(-) diff --git a/pymath/operator.py b/pymath/operator.py index 35e2a19..4d171c2 100644 --- a/pymath/operator.py +++ b/pymath/operator.py @@ -281,8 +281,32 @@ class op(object): >>> add.__txt__('1','2') '1 + 2' >>> add.__tex__('1','-2') - '1 + (-2)' + '1 - 2' """ + + def _render(self, link, *args): + """Global step for __txt__ and __tex__ + + :param link: the link between operators + :param *args: the operands + :returns: the string with operator and operands + + """ + if args[1][0] == "-": + op1 = self.l_parenthesis(args[0], True) + op2 = self.r_parenthesis(args[1][1:], True) + ans = link.replace('+','-').format(op1 = op1, op2 = op2) + + ans = save_mainOp(ans, self) + return ans + else: + op1 = self.l_parenthesis(args[0], True) + op2 = self.r_parenthesis(args[1], True) + ans = link.format(op1 = op1, op2 = op2) + + ans = save_mainOp(ans, self) + return ans + caract = { "operator" : "+", \ "name" : "add",\ @@ -291,6 +315,7 @@ class op(object): "actions" : ("__add__","__radd__"), \ "txt" : "{op1} + {op2}",\ "tex" : "{op1} + {op2}",\ + "_render": _render,\ } return caract @@ -321,6 +346,8 @@ class op(object): try: if op.mainOp.priority <= self.priority: op = flatten_list(["(", op, ")"]) + elif op[0] == '-': + op = flatten_list(["(", op, ")"]) except AttributeError: # op has not the attribute priority try: diff --git a/test/test_render.py b/test/test_render.py index 5589a2c..50394b5 100644 --- a/test/test_render.py +++ b/test/test_render.py @@ -33,7 +33,7 @@ class TestTexRender(unittest.TestCase): [-2, 3, op.add ], ] wanted_render = [ "2 + 3", - "2 + ( -3 )", + "2 - 3", "-2 + 3", ] for (i,e) in enumerate(exps): @@ -49,7 +49,7 @@ class TestTexRender(unittest.TestCase): wanted_render = [ "2 + a", "a + 3", "-2 + a", - "a + ( -2 )", + "a - 2", ] for (i,e) in enumerate(exps): rend = tex(e)