diff --git a/pymath/abstract_polynom.py b/pymath/abstract_polynom.py index 3a68782..969fcf9 100644 --- a/pymath/abstract_polynom.py +++ b/pymath/abstract_polynom.py @@ -57,6 +57,14 @@ class AbstractPolynom(Explicable): 'Q' """ super(AbstractPolynom, self).__init__() + + try: + # Remove 0 at the end of the coefs + while coefs[-1] == 0: + coefs = coefs[:-1] + except IndexError: + pass + self.feed_coef(coefs) self._letter = letter self.name = name diff --git a/pymath/polynom.py b/pymath/polynom.py index bc99854..247d476 100644 --- a/pymath/polynom.py +++ b/pymath/polynom.py @@ -8,8 +8,25 @@ from .generic import isNumerand from .random_expression import RdExpression from .abstract_polynom import AbstractPolynom +from functools import wraps +import inspect + __all__ = ["Polynom"] +def polynom_factory(func): + """ Decorator which specify the type of polynom that the function returns """ + @wraps(func) + def wrapper(*args, **kwrds): + P = func(*args, **kwrds) + if isinstance(P,Polynom) and P.degree == 2: + from .polynomDeg2 import Polynom_deg2 + new_P = Polynom_deg2(poly=P) + new_P.steps = P.steps + return new_P + else: + return P + return wrapper + class Polynom(AbstractPolynom): """Polynom view as a function. @@ -139,6 +156,15 @@ class Polynom(AbstractPolynom): ans.name = self.name + "'" return ans +# Decorate methods which may return Polynoms +methods_list = ["__add__", "__call__", "__mul__", "__neg__", "__pow__", + "__radd__", "__rmul__", "__rsub__", "__sub__", "derivate", + "reduce", "simplify", "random"] +for name, func in inspect.getmembers(Polynom): + if name in methods_list: + setattr(Polynom, name, polynom_factory(func)) + + def test(p,q): print("---------------------") print("---------------------") diff --git a/pymath/polynomDeg2.py b/pymath/polynomDeg2.py index b1e1a31..de88570 100644 --- a/pymath/polynomDeg2.py +++ b/pymath/polynomDeg2.py @@ -35,7 +35,12 @@ class Polynom_deg2(Polynom): # Création du polynom return Polynom_deg2(coefs = coefs, letter = letter, name = name) - def __init__(self, coefs = [0, 0, 1], letter = "x", name = "P"): + def __init__(self, coefs = [0, 0, 1], letter = "x", name = "P", poly = 0): + if poly: + coefs = poly._coef + letter = poly._letter + name = poly.name + if len(coefs) < 3 or len(coefs) > 4: raise ValueError("Polynom_deg2 have to be degree 2 polynoms, they need 3 coefficients, {} are given".format(len(coefs))) if coefs[2] == 0: