From 72864f12cd101330b7a84961afe32c84b7c91a19 Mon Sep 17 00:00:00 2001 From: Bertrand Benjamin Date: Sun, 28 Jan 2018 19:13:55 +0300 Subject: [PATCH] Add depth for tree --- mapytex/calculus/core/tree.py | 51 ++++++++++++++++++++++++++--------- 1 file changed, 39 insertions(+), 12 deletions(-) diff --git a/mapytex/calculus/core/tree.py b/mapytex/calculus/core/tree.py index 7b768e5..c1a57cd 100644 --- a/mapytex/calculus/core/tree.py +++ b/mapytex/calculus/core/tree.py @@ -361,9 +361,6 @@ class Tree(object): :example: - >>> nested_par = ("+", ( - ... ("*", (3, 4)), - ... 2)) >>> t = Tree.from_str("3*4+2") >>> [l for l in t.get_leafs()] [3, 4, 2] @@ -387,17 +384,10 @@ class Tree(object): :example: - >>> nested_par = ("+", ( - ... ("*", (3, 4)), - ... 2)) - >>> t = Tree.from_nested_parenthesis(nested_par) + >>> t = Tree.from_str('3*4+2') >>> [l for l in t.get_nodes()] ['+', '*'] - >>> nested_par = ("+", ( - ... ("*", (3, 4)), - ... ("*", (3, 4)) - ... )) - >>> t = Tree.from_nested_parenthesis(nested_par) + >>> t = Tree.from_str('3*4+3*4') >>> [l for l in t.get_nodes()] ['+', '*', '*'] """ @@ -411,6 +401,43 @@ class Tree(object): except AttributeError: pass + def depth(self): + """ Return the depth of the tree + + :example: + + >>> nested_par = ("+", (1, 2)) + >>> t = Tree.from_nested_parenthesis(nested_par) + >>> t.depth() + 1 + >>> nested_par = ("+", ( + ... ("*", (3, 4)), + ... 2)) + >>> t = Tree.from_nested_parenthesis(nested_par) + >>> t.depth() + 2 + >>> nested_par = ("+", ( + ... ("*", (3, + ... ("/", (4, 4)) + ... )), + ... 2)) + >>> t = Tree.from_nested_parenthesis(nested_par) + >>> t.depth() + 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 + + return 1 + max(l_depth, r_depth) + def __str__(self): """ Overload str method