move formal to polynom and solve (I hope) consequences

This commit is contained in:
Lafrite 2014-02-22 10:38:57 +01:00
parent 2e417f3bef
commit 3786bd5cf6
4 changed files with 41 additions and 42 deletions

View File

@ -4,7 +4,7 @@
from .generic import Stack, flatten_list, expand_list from .generic import Stack, flatten_list, expand_list
from .fraction import Fraction from .fraction import Fraction
from .renders import txt_render, post2in_fix, tex_render from .renders import txt_render, post2in_fix, tex_render
from .formal import FormalExp from .polynom import Polynom
class Expression(object): class Expression(object):
"""A calculus expression. Today it can andle only expression with numbers later it will be able to manipulate unknown""" """A calculus expression. Today it can andle only expression with numbers later it will be able to manipulate unknown"""
@ -143,17 +143,17 @@ class Expression(object):
# If "3x", ")x" or "yx" # If "3x", ")x" or "yx"
if self.isNumber(tokens[-1]) \ if self.isNumber(tokens[-1]) \
or tokens[-1] == ")" \ or tokens[-1] == ")" \
or type(tokens[-1]) == FormalExp: or type(tokens[-1]) == Polynom:
tokens.append("*") tokens.append("*")
tokens.append(FormalExp(letter = character)) tokens.append(Polynom(letter = character))
# Special case for "-" at the begining of an expression or before "(" # Special case for "-" at the begining of an expression or before "("
elif tokens[-1] == "-" \ elif tokens[-1] == "-" \
or str(tokens[-2]) in " (": or str(tokens[-2]) in " (":
tokens[-1] = - FormalExp(letter = character) tokens[-1] = - Polynom(letter = character)
else: else:
tokens.append(FormalExp(letter = character)) tokens.append(Polynom(letter = character))
elif character in "+-*/):^": elif character in "+-*/):^":
tokens.append(character) tokens.append(character)
@ -162,7 +162,7 @@ class Expression(object):
# If "3(", ")(" or "x(" # If "3(", ")(" or "x("
if self.isNumber(tokens[-1]) \ if self.isNumber(tokens[-1]) \
or tokens[-1] == ")" \ or tokens[-1] == ")" \
or type(tokens[-1]) == FormalExp: or type(tokens[-1]) == Polynom:
tokens.append("*") tokens.append("*")
tokens.append(character) tokens.append(character)
@ -324,7 +324,7 @@ class Expression(object):
""" """
return type(exp) == int or \ return type(exp) == int or \
type(exp) == Fraction or \ type(exp) == Fraction or \
type(exp) == FormalExp type(exp) == Polynom
@staticmethod @staticmethod
def isOperator(exp): def isOperator(exp):

View File

@ -5,11 +5,11 @@ from .fraction import Fraction
from .generic import add_in_dict, remove_in_dict, convolution_dict from .generic import add_in_dict, remove_in_dict, convolution_dict
import re import re
class FormalExp(object): class Polynom(object):
"""A formal expression (similare to Symbol in Sympy""" """A polynom (similare to Symbol in Sympy"""
def __init__(self, coef = {}, letter = ""): def __init__(self, coef = {}, letter = ""):
"""Initiat the formal expression """Initiat the polynom
:param coef: the dictionary representing the expression :param coef: the dictionary representing the expression
:param letter: minimum expression, a letter :param letter: minimum expression, a letter
@ -17,14 +17,14 @@ class FormalExp(object):
""" """
if coef != {} and letter != "": if coef != {} and letter != "":
raise ValueError("A FormalExp can't be initiate with dict_exp and a letter") raise ValueError("A Polynom can't be initiate with dict_exp and a letter")
elif letter != "": elif letter != "":
self._letter = letter self._letter = letter
self._coef = {letter: 1} self._coef = {letter: 1}
elif coef != {}: elif coef != {}:
self._coef = coef self._coef = coef
else: else:
raise ValueError("FormalExp needs a letter or dictionary of coeficients") raise ValueError("Polynom needs a letter or dictionary of coeficients")
if len(self) != 1: if len(self) != 1:
self.mainOp = "+" self.mainOp = "+"
@ -52,7 +52,7 @@ class FormalExp(object):
return power[m_power] return power[m_power]
def check_calculous(self, other): def check_calculous(self, other):
"""Check if other is a constant and then transform it into a dictionary compatible with FormalExp """Check if other is a constant and then transform it into a dictionary compatible with Polynom
:param other: The thing to compute with the expression :param other: The thing to compute with the expression
:returns: dictionary of this thing :returns: dictionary of this thing
@ -60,22 +60,22 @@ class FormalExp(object):
""" """
if type(other) in [int, Fraction]: if type(other) in [int, Fraction]:
return {"":other} return {"":other}
elif type(other) == FormalExp: elif type(other) == Polynom:
return other._coef.copy() return other._coef.copy()
else: else:
raise ValueError("Can't add {type} with FormalExp".format(type=type(other))) raise ValueError("Can't add {type} with Polynom".format(type=type(other)))
def const_or_formal(self, d): def const_or_poly(self, d):
"""Return a constant if there is nothing else, FormalExp otherwise """Return a constant if there is nothing else, Polynom otherwise
:param d: dictionary descripting the expression :param d: dictionary descripting the expression
:returns: a constant or a FormalExp :returns: a constant or a Polynom
""" """
if list(d.keys()) == ['']: if list(d.keys()) == ['']:
return d[''] return d['']
else: else:
return FormalExp(d) return Polynom(d)
def __add__(self, other): def __add__(self, other):
d = self.check_calculous(other) d = self.check_calculous(other)
@ -83,7 +83,7 @@ class FormalExp(object):
d = add_in_dict(self._coef, d) d = add_in_dict(self._coef, d)
d = remove_in_dict(d) d = remove_in_dict(d)
return [self.const_or_formal(d)] return [self.const_or_poly(d)]
def __radd__(self, other): def __radd__(self, other):
return self + other return self + other
@ -96,7 +96,7 @@ class FormalExp(object):
d = {} d = {}
for k,v in self._coef.items(): for k,v in self._coef.items():
d[k] = -v d[k] = -v
return FormalExp(d) return Polynom(d)
def __mul__(self, other): def __mul__(self, other):
d = self.check_calculous(other) d = self.check_calculous(other)
@ -104,15 +104,7 @@ class FormalExp(object):
d = convolution_dict(self._coef, d, op_key = self.op_key) d = convolution_dict(self._coef, d, op_key = self.op_key)
d = remove_in_dict(d) d = remove_in_dict(d)
return [self.const_or_formal(d)] return [self.const_or_poly(d)]
def op_key(self, x,y):
"""Operation on keys for convolution_dict"""
if x == "" or y == "":
return x+y
else:
return x + "*" + y
def __rmul__(self, other): def __rmul__(self, other):
d = self.check_calculous(other) d = self.check_calculous(other)
@ -120,7 +112,14 @@ class FormalExp(object):
d = convolution_dict(d, self._coef, op_key = self.op_key) d = convolution_dict(d, self._coef, op_key = self.op_key)
d = remove_in_dict(d) d = remove_in_dict(d)
return [self.const_or_formal(d)] return [self.const_or_poly(d)]
def op_key(self, x,y):
"""Operation on keys for convolution_dict"""
if x == "" or y == "":
return x+y
else:
return x + "*" + y
def __div__(self, other): def __div__(self, other):
# Will never be done :D # Will never be done :D
@ -151,9 +150,9 @@ class FormalExp(object):
return ans return ans
if __name__ == '__main__': if __name__ == '__main__':
fe1 = FormalExp({"x": -1, "":-2}) fe1 = Polynom({"x": -1, "":-2})
print(fe1) print(fe1)
fe2 = FormalExp({"x^12": 5, "":2}) fe2 = Polynom({"x^12": 5, "":2})
print(fe2) print(fe2)
fe3 = fe1 * fe2 fe3 = fe1 * fe2
for s in fe3: for s in fe3:
@ -162,11 +161,11 @@ if __name__ == '__main__':
for s in fe4: for s in fe4:
print(s) print(s)
fe = FormalExp(letter = "a") fe = Polynom(letter = "a")
fe_ = -2 * fe fe_ = -2 * fe
print(fe_[0]) print(fe_[0])
fe = FormalExp(letter = "a") fe = Polynom(letter = "a")
fe_ = fe * (-2) fe_ = fe * (-2)
print(fe_[0]) print(fe_[0])

View File

@ -3,7 +3,7 @@
from .generic import Stack,flatten_list from .generic import Stack,flatten_list
from .fraction import Fraction from .fraction import Fraction
from .formal import FormalExp from .polynom import Polynom
class Render(object): class Render(object):
"""A class which aims to create render functions from three dictionnaries: """A class which aims to create render functions from three dictionnaries:
@ -15,7 +15,7 @@ class Render(object):
PRIORITY = {"^": 4,"*" : 3, "/": 3, ":": 3, "+": 2, "-":2, "(": 1} PRIORITY = {"^": 4,"*" : 3, "/": 3, ":": 3, "+": 2, "-":2, "(": 1}
def __init__(self, op_infix = {}, op_postfix = {}, other = {}, join = " ", type_render = {int: str, Fraction: str, FormalExp: str}): def __init__(self, op_infix = {}, op_postfix = {}, other = {}, join = " ", type_render = {int: str, Fraction: str, Polynom: str}):
"""Initiate the render """Initiate the render
@param op_infix: the dictionnary of infix operator with how they have to be render @param op_infix: the dictionnary of infix operator with how they have to be render
@ -118,7 +118,7 @@ class Render(object):
return 1 return 1
# Si c'est un expression formelle # Si c'est un expression formelle
elif type(operande) == FormalExp: elif type(operande) == Polynom:
if operator in ["*", "/", "^"]: if operator in ["*", "/", "^"]:
if len(operande) > 1 \ if len(operande) > 1 \
or operande.master_coef() < 0: or operande.master_coef() < 0:
@ -190,7 +190,7 @@ class Render(object):
""" """
return type(exp) == int \ return type(exp) == int \
or type(exp) == Fraction \ or type(exp) == Fraction \
or type(exp) == FormalExp or type(exp) == Polynom
def isOperator(self, exp): def isOperator(self, exp):
"""Check if the expression is in self.operators """Check if the expression is in self.operators

View File

@ -3,7 +3,7 @@
from .render import Render from .render import Render
from .fraction import Fraction from .fraction import Fraction
from .formal import FormalExp from .polynom import Polynom
from .generic import first_elem from .generic import first_elem
# ------------------------ # ------------------------
@ -39,7 +39,7 @@ def texFrac(frac):
def texMult(op1,op2): def texMult(op1,op2):
fe = first_elem(op2) fe = first_elem(op2)
if type(fe) == FormalExp or fe.isalpha(): if type(fe) == Polynom or fe.isalpha():
if type(op1) == list and op1[0] == "(": if type(op1) == list and op1[0] == "(":
return ["(", op1[1:-1], op2, ")"] return ["(", op1[1:-1], op2, ")"]
else: else:
@ -50,7 +50,7 @@ def texMult(op1,op2):
tex_infix = {"+": " + ", "-": " - ", "*": texMult , ":": ":", "^":"^"} tex_infix = {"+": " + ", "-": " - ", "*": texMult , ":": ":", "^":"^"}
tex_postfix = {"/": texSlash} tex_postfix = {"/": texSlash}
tex_other = {"(": "(", ")": ")"} tex_other = {"(": "(", ")": ")"}
tex_type_render = {int: str, Fraction: texFrac, FormalExp: str} tex_type_render = {int: str, Fraction: texFrac, Polynom: str}
tex_render = Render(tex_infix, tex_postfix, tex_other, type_render = tex_type_render) tex_render = Render(tex_infix, tex_postfix, tex_other, type_render = tex_type_render)