From 4d75361c9daa2987a82bddeb1622f947a16895c8 Mon Sep 17 00:00:00 2001 From: Bertrand Benjamin Date: Mon, 1 Oct 2018 17:36:12 +0200 Subject: [PATCH] Feat(Tree): Deep and short branch property for trees --- mapytex/calculus/core/tree.py | 89 +++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) diff --git a/mapytex/calculus/core/tree.py b/mapytex/calculus/core/tree.py index e84df16..cfe8b6c 100644 --- a/mapytex/calculus/core/tree.py +++ b/mapytex/calculus/core/tree.py @@ -567,6 +567,95 @@ class Tree(object): """ return self.apply(postfix_concatenate) + @property + def short_branch(self): + """ Get the short branch of the tree, left if same depth + + :return: A tree or a leaf value + + :example: + >>> t = Tree.from_str("2+3*4") + >>> print(t.short_branch) + 2 + >>> t = Tree.from_str("1*2*3+4*5") + >>> print(t.short_branch) + * + > 4 + > 5 + >>> t = Tree.from_str("2*3+4*5") + >>> print(t) + + + > * + | > 2 + | > 3 + > * + | > 4 + | > 5 + >>> print(t.short_branch) + * + > 2 + > 3 + """ + try: + l_depth = self.left_value.depth() + except AttributeError: + l_depth = 0 + try: + r_depth = self.right_value.depth() + except AttributeError: + r_depth = 0 + + if l_depth <= r_depth: + return self.left_value + else: + return self.right_value + + @property + def deep_branch(self): + """ Get the deep branch of the tree, right if same depth + + :return: A tree or a leaf value + + :example: + >>> t = Tree.from_str("2+3*4") + >>> print(t.deep_branch) + * + > 3 + > 4 + >>> t = Tree.from_str("2*3+4*5") + >>> print(t) + + + > * + | > 2 + | > 3 + > * + | > 4 + | > 5 + >>> print(t.deep_branch) + * + > 4 + > 5 + >>> t = Tree.from_str("2*3+4") + >>> print(t.deep_branch) + * + > 2 + > 3 + """ + try: + l_depth = self.left_value.depth() + except AttributeError: + l_depth = 0 + try: + r_depth = self.right_value.depth() + except AttributeError: + r_depth = 0 + + if l_depth <= r_depth: + return self.right_value + else: + return self.left_value + + class MutableTree(Tree): """