From 5b9a35081a87a2e14128694f1fc4273e6304de20 Mon Sep 17 00:00:00 2001 From: Bertrand Benjamin Date: Mon, 12 Nov 2018 09:41:39 +0100 Subject: [PATCH] Feat(MO): Start polynomial --- mapytex/calculus/core/MO/polynomial.py | 75 ++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 mapytex/calculus/core/MO/polynomial.py diff --git a/mapytex/calculus/core/MO/polynomial.py b/mapytex/calculus/core/MO/polynomial.py new file mode 100644 index 0000000..210669b --- /dev/null +++ b/mapytex/calculus/core/MO/polynomial.py @@ -0,0 +1,75 @@ +#! /usr/bin/env python +# -*- coding: utf-8 -*- +# vim:fenc=utf-8 +# +# Copyright © 2017 lafrite +# +# Distributed under terms of the MIT license. + +from mapytex.calculus.core.tree import Tree +from .mo import MO, MOnumber, MOstr +from .exceptions import MOError +from ..renders import tree2txt, tree2tex + +__all__ = ["MOpolynomial"] + +class MOpolynomial(MO): + + """ MO polynomial""" + + def __init__(self, variable, coefs): + """ Initiate a MOpolynomial + + :param variable: variable of the monomial (a MOstr or later a MOSqrt) + :param coefs: dictionnary {deg: coef} or a list [coef0, coef1...] + + :example: + >>> MOpolynomial('x', [1, 2, 3]) + 3x^2 + 2x + 1 + >>> MOpolynomial('x', [1, 0, 3]) + 3x^2 + 1 + >>> MOpolynomial('x', {0: 1, 1: 2, 2: 3}) + 3x^2 + 2x + 1 + >>> MOpolynomial('x', {0: 1, 3: 4}) + 4x^3 + 1 + + + """ + _variable = MO.factory(variable) + if not isinstance(_variable, MOstr): + raise MOError("The variable of a monomial should be convertible into MOstr") + self._variable = _variable + + if isinstance(coefs, dict): + _coefs = {MO.factory(d): MO.factory(c) for (d, c) in coefs} + elif isinstance(coefs, list): + _coefs = {MO.factory(d): MO.factory(c) for (d, c) in enumerate(coefs)} + else: + raise TypeError("Coefs needs to be a dictionnary or a list") + self._coefs = _coefs + + monomials = [] + for deg, coef in self._coefs: + if deg == 0: + monomials.append(coef) + elif deg == 1: + monomials.append(coef) + value = Tree("^", + self._variable, + self._power + ) + MO.__init__(self, value) + + @property + def variable(self): + return self._variable + + @property + def degree(self): + return self._power + + +# ----------------------------- +# Reglages pour 'vim' +# vim:set autoindent expandtab tabstop=4 shiftwidth=4: +# cursor: 16 del