remove everything about polynoms

This commit is contained in:
Lafrite 2014-02-28 09:43:54 +01:00
parent f444a58a2b
commit ab83751e57
5 changed files with 5 additions and 246 deletions

View File

@ -4,7 +4,6 @@
from .generic import Stack, flatten_list, expand_list
from .fraction import Fraction
from .renders import txt_render, post2in_fix, tex_render
from .polynom import Polynom
__all__ = ['Expression']
@ -141,30 +140,13 @@ class Expression(object):
else:
tokens.append(int(character))
elif character.isalpha():
# If "3x", ")x" or "yx"
if self.isNumber(tokens[-1]) \
or tokens[-1] == ")" \
or type(tokens[-1]) == Polynom:
tokens.append("*")
tokens.append(Polynom(letter = character))
# Special case for "-" at the begining of an expression or before "("
elif tokens[-1] == "-" \
or str(tokens[-2]) in " (":
tokens[-1] = - Polynom(letter = character)
else:
tokens.append(Polynom(letter = character))
elif character in "+-*/):^":
tokens.append(character)
elif character in "(":
# If "3(", ")(" or "x("
# If "3(", ")("
if self.isNumber(tokens[-1]) \
or tokens[-1] == ")" \
or type(tokens[-1]) == Polynom:
or tokens[-1] == ")" :
tokens.append("*")
tokens.append(character)
@ -325,8 +307,7 @@ class Expression(object):
"""
return type(exp) == int or \
type(exp) == Fraction or \
type(exp) == Polynom
type(exp) == Fraction
@staticmethod
def isOperator(exp):
@ -397,13 +378,6 @@ if __name__ == '__main__':
#exp="-2*4(12 + 1)(3-12)"
#test(exp)
exp="-2+a+(12 + 1)(3-12) / 34a"
#test(exp)
e = Expression(exp)
print(e.render(render = tex_render))
#exp="-2*b+a(12 + 1)(3-12)"
#test(exp)
#exp="(-2+5)/(3*4)+1/12+5*5"
#test(exp)
@ -413,22 +387,6 @@ if __name__ == '__main__':
#e = Expression(exp)
#print(e)
exp="-2+a+(12 + 1)(3-12) : 34a"
#test(exp)
#exp="-2+a+(12 + 1)(3-12) : 34a"
##test(exp)
#e = Expression(exp)
#print(e.render(render = tex_render))
#exp="-2*b+a(12 + 1)(3-12)"
#test(exp)
# TODO: The next one doesn't work |ven. janv. 17 14:56:58 CET 2014
#exp="-2*(-a)(12 + 1)(3-12)"
#e = Expression(exp)
#print(e)
## Can't handle it yet!!
#exp="-(-2)"
#test(exp)

View File

@ -1,180 +0,0 @@
#!/usr/bin/env python
# encoding: utf-8
from .fraction import Fraction
from .generic import add_in_dict, remove_in_dict, convolution_dict
import re
__all__ = ['Polynom']
class Polynom(object):
"""A polynom (similare to Symbol in Sympy"""
def __init__(self, coef = {}, letter = ""):
"""Initiat the polynom
:param coef: the dictionary representing the expression
:param letter: minimum expression, a letter
"""
if coef != {} and letter != "":
raise ValueError("A Polynom can't be initiate with dict_exp and a letter")
elif letter != "":
self._letter = letter
self._coef = {letter: 1}
elif coef != {}:
self._coef = coef
else:
raise ValueError("Polynom needs a letter or dictionary of coeficients")
if len(self) != 1:
self.mainOp = "+"
def master_coef(self):
"""Return the master coefficient
/!\ may not work pretty well if there is more than one indeterminate
:returns: a_n
"""
pattern = "\w\^(\d*)"
finder = re.compile(pattern)
power = {}
for (k,v) in self._coef.items():
if k=="":
power[0] = v
else:
p = finder.findall(k)
if p == []:
power[1] = v
else:
power[int(p[0])] = v
m_power = max(power)
return power[m_power]
def check_calculous(self, other):
"""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
:returns: dictionary of this thing
"""
if type(other) in [int, Fraction]:
return {"":other}
elif type(other) == Polynom:
return other._coef.copy()
else:
raise ValueError("Can't add {type} with Polynom".format(type=type(other)))
def const_or_poly(self, d):
"""Return a constant if there is nothing else, Polynom otherwise
:param d: dictionary descripting the expression
:returns: a constant or a Polynom
"""
if list(d.keys()) == ['']:
return d['']
else:
return Polynom(d)
def __add__(self, other):
d = self.check_calculous(other)
d = add_in_dict(self._coef, d)
d = remove_in_dict(d)
return [self.const_or_poly(d)]
def __radd__(self, other):
return self + other
def __sub__(self, other):
o_tmp = -other
return self + o_tmp
def __neg__(self):
d = {}
for k,v in self._coef.items():
d[k] = -v
return Polynom(d)
def __mul__(self, other):
d = self.check_calculous(other)
d = convolution_dict(self._coef, d, op_key = self.op_key)
d = remove_in_dict(d)
return [self.const_or_poly(d)]
def __rmul__(self, other):
d = self.check_calculous(other)
d = convolution_dict(d, self._coef, op_key = self.op_key)
d = remove_in_dict(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):
# Will never be done :D
pass
def __pow__(self, other):
# Will never be done :D quoique
pass
def __len__(self):
return len(list(self._coef.keys()))
def __str__(self):
ans = ""
for k,v in self._coef.items():
if v < 0:
ans += "-"
else:
ans += "+"
if abs(v) == 1:
ans += str(k)
else:
ans += str(abs(v)) + str(k)
if ans[0] == "+":
return ans[1:]
else:
return ans
if __name__ == '__main__':
fe1 = Polynom({"x": -1, "":-2})
print(fe1)
fe2 = Polynom({"x^12": 5, "":2})
print(fe2)
fe3 = fe1 * fe2
for s in fe3:
print(s)
fe4 = fe1 * 2
for s in fe4:
print(s)
fe = Polynom(letter = "a")
fe_ = -2 * fe
print(fe_[0])
fe = Polynom(letter = "a")
fe_ = fe * (-2)
print(fe_[0])
# -----------------------------
# Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4:
# cursor: 16 del

View File

@ -3,7 +3,6 @@
from .generic import Stack,flatten_list
from .fraction import Fraction
from .polynom import Polynom
__all__ = ['Render']
@ -17,7 +16,7 @@ class Render(object):
PRIORITY = {"^": 4,"*" : 3, "/": 3, ":": 3, "+": 2, "-":2, "(": 1}
def __init__(self, op_infix = {}, op_postfix = {}, other = {}, join = " ", type_render = {str: str, int: str, Fraction: str, Polynom: str}):
def __init__(self, op_infix = {}, op_postfix = {}, other = {}, join = " ", type_render = {str: str, int: str, Fraction: str}):
"""Initiate the render
@param op_infix: the dictionnary of infix operator with how they have to be render
@ -124,15 +123,6 @@ class Render(object):
or type(operande) == Fraction:
return 0
# Si c'est un polynom
elif type(operande) == Polynom:
if operator in ["*", "/", "^"]:
if len(operande) > 1 \
or operande.master_coef() < 0:
return 1
else:
return 0
elif not self.isNumber(operande):
# Si c'est une grande expression
stand_alone = self.get_main_op(operande)
@ -197,7 +187,6 @@ class Render(object):
"""
return type(exp) == int \
or type(exp) == Fraction \
or type(exp) == Polynom \
or exp.isalpha()
def isOperator(self, exp):

View File

@ -3,7 +3,6 @@
from .render import Render
from .fraction import Fraction
from .polynom import Polynom
from .generic import first_elem, last_elem
__all__ = ['post2in_fix', 'tex_render', 'txt_render']
@ -80,7 +79,7 @@ def texMult(op1,op2):
tex_infix = {"+": " + ", "-": " - ", "*": texMult , ":": ":", "^":"^"}
tex_postfix = {"/": texSlash}
tex_other = {"(": "(", ")": ")"}
tex_type_render = {str:str, int: str, Fraction: texFrac, Polynom: str}
tex_type_render = {str:str, int: str, Fraction: texFrac}
tex_render = Render(tex_infix, tex_postfix, tex_other, type_render = tex_type_render)

View File

@ -6,7 +6,6 @@ import unittest
from pymath.renders import tex_render, txt_render
from pymath.fraction import Fraction
from pymath.polynom import Polynom
@ -22,9 +21,6 @@ class TestTexRender(unittest.TestCase):
def test_type_render_fraction(self):
self.assertEqual(tex_render([Fraction(1,2)]), "\\frac{ 1 }{ 2 }")
def test_type_render_polynom(self):
self.assertEqual(tex_render([Polynom({"": 1, "x": 3})]), "3x + 1")
def test_mult_interger(self):
exps = [ [2, 3, "*"], [2, -3, "*"], [-2, 3, "*"]]
wanted_render = [ "2 \\times 3", "2 \\times ( -3 )", "-2 \\times 3"]
@ -67,9 +63,6 @@ class TesttxtRender(unittest.TestCase):
def test_type_render_fraction(self):
self.assertEqual(txt_render([Fraction(1,2)]), "1 / 2")
def test_type_render_polynom(self):
self.assertEqual(txt_render([Polynom({"": 1, "x": 3})]), "3x + 1")
def test_mult_interger(self):
exps = [ [2, 3, "*"], [2, -3, "*"], [-2, 3, "*"]]
wanted_render = [ "2 * 3", "2 * ( -3 )", "-2 * 3"]