Feat: Expression call works with tokens

This commit is contained in:
Bertrand Benjamin 2019-07-16 09:30:30 +02:00
parent 9f492378c8
commit 3e258b2d41

View File

@ -442,6 +442,9 @@ class Expression(object):
def __call__(self, value):
""" Call a Expression to evaluate itself on value
:param value: evaluate the Expression with this value
:return: Expression simplified if the value is not a string with a length greater than 1.
:examples:
>>> f = Expression.from_str("3*x^2 + 2x + 1")
>>> for s in f(2).explain():
@ -450,14 +453,27 @@ class Expression(object):
3 * 4 + 4 + 1
12 + 5
17
>>> f(f(2))
<Integer 902>
>>> f(17)
<Integer 902>
>>> f("n")
<Quadratic 3n^2 + 2n + 1>
>>> f("u_n")
<Exp: 3u_n^2 + 2u_n + 1>
"""
tree = self._tree
variable = (set(tree.get_leafs(extract_variable)) - {None}).pop()
dest = moify(value)
try:
dest = value._mo
except AttributeError:
dest = moify(value)
replace_var = partial(replace, origin=variable, dest=dest)
tree = tree.map_on_leaf(replace_var)
if isinstance(value, str) and len(value) > 1:
return Expression(tree)
return Expression(tree).simplify()