From fa8beb6bb2a8fde045b6e71b8f9373a1922a9f8b Mon Sep 17 00:00:00 2001 From: Bertrand Benjamin Date: Mon, 15 Jul 2019 11:14:48 +0200 Subject: [PATCH] Feat: Polynomial can be evaluated --- mapytex/calculus/API/tokens/polynomial.py | 34 +++++++++++++++++++---- 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/mapytex/calculus/API/tokens/polynomial.py b/mapytex/calculus/API/tokens/polynomial.py index 4252e7e..e765a5e 100644 --- a/mapytex/calculus/API/tokens/polynomial.py +++ b/mapytex/calculus/API/tokens/polynomial.py @@ -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 + """ 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: