Feat(Expression): Implement balance in expression

This commit is contained in:
Bertrand Benjamin 2018-10-04 08:16:59 +02:00
parent 89d7baaed2
commit 948402755a
1 changed files with 6 additions and 96 deletions

View File

@ -88,95 +88,6 @@ class Expression(object):
def __repr__(self):
return f"<Exp: {renders[self.RENDER](self._tree)}>"
def balance(self):
""" Balance selt._tree in order to optimize end tree number
# TODO: their will be issue with / which is not commutative |lun. oct. 1 15:03:21 CEST 2018
:return: optmized version of self
:example:
>>> t = Expression.from_str("1+2+3+4+5+6+7+8+9")
>>> print(t._tree)
+
> +
| > +
| | > +
| | | > +
| | | | > +
| | | | | > +
| | | | | | > +
| | | | | | | > 1
| | | | | | | > 2
| | | | | | > 3
| | | | | > 4
| | | | > 5
| | | > 6
| | > 7
| > 8
> 9
>>> t.balance()
>>> print(t._tree)
+
> +
| > +
| | > 1
| | > 2
| > +
| | > 3
| | > 4
> +
| > +
| | > 5
| | > 6
| > +
| | > 7
| | > +
| | | > 8
| | | > 9
>>> t = Expression.from_str("1+2+3+4+5*6*7*8*9")
>>> print(t._tree)
+
> +
| > +
| | > +
| | | > 1
| | | > 2
| | > 3
| > 4
> *
| > *
| | > *
| | | > *
| | | | > 5
| | | | > 6
| | | > 7
| | > 8
| > 9
>>> t.balance()
>>> print(t._tree)
+
> +
| > 1
| > 2
> +
| > 3
| > +
| | > 4
| | > *
| | | > *
| | | | > 5
| | | | > 6
| | | > *
| | | | > 7
| | | | > *
| | | | | > 8
| | | | | > 9
"""
self._tree = AssocialTree.from_any_tree(self._tree).balance()
def simplify(self, optimize=True):
""" Compute as much as possible the expression
@ -195,7 +106,7 @@ class Expression(object):
"""
if optimize:
try:
self.balance()
self._tree = self._tree.balance()
except AttributeError:
pass
try:
@ -224,9 +135,9 @@ class Expression(object):
>>> for s in f.explain():
... print(s)
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9
3 + 7 + 11 + 7 + 17
10 + 11 + 24
10 + 35
3 + 3 + 9 + 6 + 7 + 17
6 + 9 + 6 + 24
15 + 30
45
>>> e = Expression.from_str("1+2+3+4+5+6+7+8+9")
>>> f_no_balance = e.simplify(optimize=False)
@ -247,9 +158,8 @@ class Expression(object):
... print(s)
1 + 2 + 3 + 4 + 5 * 6 * 7 * 8 * 9
3 + 3 + 4 + 30 * 7 * 72
6 + 4 + 30 * 504
6 + 4 + 15120
6 + 15124
6 + 4 + 210 * 72
10 + 15120
15130
>>> e = Expression.from_str("1+2+3+4+5*6*7*8*9")
>>> f_no_balance = e.simplify(optimize=False)