Feat(Tree): Deep and short branch property for trees

This commit is contained in:
Bertrand Benjamin 2018-10-01 17:36:12 +02:00
parent e9a865a14a
commit 4d75361c9d

View File

@ -567,6 +567,95 @@ class Tree(object):
""" """
return self.apply(postfix_concatenate) 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): class MutableTree(Tree):
""" """