Feat: Polynomial can be evaluated

This commit is contained in:
Bertrand Benjamin 2019-07-15 11:14:48 +02:00
parent b81281d78a
commit fa8beb6bb2

View File

@ -10,8 +10,11 @@
Tokens representing polynomials functions
"""
from ..expression import Expression
from functools import partial
from .token import Token
from ...core.MO import MO
from ...core.MO.atoms import moify
__all__ = ["Polynomial", "Quadratic", "Linear"]
@ -24,6 +27,7 @@ class Polynomial(Token):
>>> from ...core.MO.polynomial import MOpolynomial
>>> P = Polynomial(MOpolynomial('x', [1, 2, 3]))
>>> P
<Polynomial 3x^2 + 2x + 1>
"""
def __init__(self, a, name="", ancestor=None):
@ -61,9 +65,21 @@ class Polynomial(Token):
:examples:
>>> from ...core.MO.polynomial import MOpolynomial
>>> P = Polynomial(MOpolynomial('x', [1, 2, 3]))
>>> P(2)
>>> for s in P(2).explain():
... print(s)
3 * 2^2 + 2 * 2 + 1
3 * 4 + 4 + 1
12 + 5
17
"""
pass
tree = self._mo.tree
variable = (set(tree.get_leafs(extract_variable)) - {None}).pop()
dest = moify(value)
replace_var = partial(replace, origin=variable, dest=dest)
tree = tree.map_on_leaf(replace_var)
return Expression(tree).simplify()
class Linear(Polynomial):
@ -101,10 +117,16 @@ def extract_variable(leaf):
return None
def replace(leaf, origin, dest):
# map_on_leaf sur leaf?
if leaf == origin:
return dest
return leaf
""" Recursively replace origin to dest in leaf """
try:
leaf.tree
except AttributeError:
if leaf == origin:
return dest
return leaf
replace_var = partial(replace, origin=origin, dest=dest)
return leaf.tree.map_on_leaf(replace_var)
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: