From f037d5545fd921f6f49cf5dc70e93392322bfa14 Mon Sep 17 00:00:00 2001 From: Bertrand Benjamin Date: Fri, 28 Jun 2019 11:30:54 +0200 Subject: [PATCH] Fix: Clean tree2tex by copying tree2txt --- mapytex/calculus/core/renders/tree2tex.py | 44 ++++++++++++----------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/mapytex/calculus/core/renders/tree2tex.py b/mapytex/calculus/core/renders/tree2tex.py index 84d41d5..651912c 100644 --- a/mapytex/calculus/core/renders/tree2tex.py +++ b/mapytex/calculus/core/renders/tree2tex.py @@ -29,23 +29,13 @@ def plus2tex(left, right): >>> plus2tex(MO.factory(3), t) '3 - 2 \\times 3' """ - display_plus = True - try: - left.node - except AttributeError: - left_ = left.__tex__ - else: - left_ = tree2tex(left) - try: - right.node - except AttributeError: - right_ = right.__tex__ - else: - right_ = tree2tex(right) - finally: - if right_.startswith("-"): - display_plus = False + left_ = render_with_parenthesis(left, "+") + right_ = render_with_parenthesis(right, "+") + + display_plus = True + if right_.startswith("-"): + display_plus = False if display_plus: return f"{left_} + {right_}" @@ -97,6 +87,8 @@ def mul2tex(left, right): >>> a = MO.factory('x') >>> mul2tex(MO.factory(3), a) '3x' + >>> mul2tex(MO.factory(-3), a) + '- 3x' >>> mul2tex(a, a) 'x \\times x' """ @@ -104,9 +96,15 @@ def mul2tex(left, right): right_ = render_with_parenthesis(right, "*") display_time = True - if (right_[0].isalpha() and (left_.isnumeric() or left_.isdecimal())) or right_[ - 0 - ] == "(": + # if (right_[0].isalpha() and (left_.isnumeric() or left_.isdecimal())) or right_[ + # 0 + # ] == "(": + # display_time = False + if right_[0].isalpha(): + # TODO: C'est bien beurk en dessous... |ven. déc. 21 12:03:07 CET 2018 + if type(left).__name__ == "MOnumber": + display_time = False + elif right_[0] == "(": display_time = False if display_time: @@ -133,11 +131,11 @@ def div2tex(left, right): """ try: left_ = tree2tex(left) - except AttributeError: + except (AttributeError, ValueError): left_ = left.__tex__ try: right_ = tree2tex(right) - except AttributeError: + except (AttributeError, ValueError): right_ = right.__tex__ return "\\frac{" + left_ + "}{" + right_ + "}" @@ -226,6 +224,10 @@ def tree2tex(tree): >>> tree2tex(t) '2 + 3 \\times 4' """ + from ..tree import Tree + + if not isinstance(tree, Tree): + raise ValueError(f"Can only render a Tree (got {type(tree).__name__}: {tree})") return OPERATOR2TEX[tree.node](tree.left_value, tree.right_value)