Polynom factory to produce Deg 2 poly!

This commit is contained in:
Lafrite 2015-04-03 17:32:02 +02:00
parent 045b28b1e5
commit ec735175f7
3 changed files with 40 additions and 1 deletions

View File

@ -57,6 +57,14 @@ class AbstractPolynom(Explicable):
'Q' 'Q'
""" """
super(AbstractPolynom, self).__init__() 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.feed_coef(coefs)
self._letter = letter self._letter = letter
self.name = name self.name = name

View File

@ -8,8 +8,25 @@ from .generic import isNumerand
from .random_expression import RdExpression from .random_expression import RdExpression
from .abstract_polynom import AbstractPolynom from .abstract_polynom import AbstractPolynom
from functools import wraps
import inspect
__all__ = ["Polynom"] __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): class Polynom(AbstractPolynom):
"""Polynom view as a function. """Polynom view as a function.
@ -139,6 +156,15 @@ class Polynom(AbstractPolynom):
ans.name = self.name + "'" ans.name = self.name + "'"
return ans 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): def test(p,q):
print("---------------------") print("---------------------")
print("---------------------") print("---------------------")

View File

@ -35,7 +35,12 @@ class Polynom_deg2(Polynom):
# Création du polynom # Création du polynom
return Polynom_deg2(coefs = coefs, letter = letter, name = name) 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: 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))) raise ValueError("Polynom_deg2 have to be degree 2 polynoms, they need 3 coefficients, {} are given".format(len(coefs)))
if coefs[2] == 0: if coefs[2] == 0: