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

View File

@ -88,95 +88,6 @@ class Expression(object):
def __repr__(self): def __repr__(self):
return f"<Exp: {renders[self.RENDER](self._tree)}>" 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): def simplify(self, optimize=True):
""" Compute as much as possible the expression """ Compute as much as possible the expression
@ -195,7 +106,7 @@ class Expression(object):
""" """
if optimize: if optimize:
try: try:
self.balance() self._tree = self._tree.balance()
except AttributeError: except AttributeError:
pass pass
try: try:
@ -224,9 +135,9 @@ class Expression(object):
>>> for s in f.explain(): >>> for s in f.explain():
... print(s) ... print(s)
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9
3 + 7 + 11 + 7 + 17 3 + 3 + 9 + 6 + 7 + 17
10 + 11 + 24 6 + 9 + 6 + 24
10 + 35 15 + 30
45 45
>>> e = Expression.from_str("1+2+3+4+5+6+7+8+9") >>> e = Expression.from_str("1+2+3+4+5+6+7+8+9")
>>> f_no_balance = e.simplify(optimize=False) >>> f_no_balance = e.simplify(optimize=False)
@ -247,9 +158,8 @@ class Expression(object):
... print(s) ... print(s)
1 + 2 + 3 + 4 + 5 * 6 * 7 * 8 * 9 1 + 2 + 3 + 4 + 5 * 6 * 7 * 8 * 9
3 + 3 + 4 + 30 * 7 * 72 3 + 3 + 4 + 30 * 7 * 72
6 + 4 + 30 * 504 6 + 4 + 210 * 72
6 + 4 + 15120 10 + 15120
6 + 15124
15130 15130
>>> e = Expression.from_str("1+2+3+4+5*6*7*8*9") >>> e = Expression.from_str("1+2+3+4+5*6*7*8*9")
>>> f_no_balance = e.simplify(optimize=False) >>> f_no_balance = e.simplify(optimize=False)