flake8 corr (not finish yet)

This commit is contained in:
Benjamin Bertrand 2016-03-06 18:18:01 +03:00
parent b6da1e24a1
commit edd83fe56a
14 changed files with 95 additions and 275 deletions

View File

@ -4,8 +4,7 @@
from .explicable import Explicable from .explicable import Explicable
from .expression import Expression from .expression import Expression
from .operator import op from .operator import op
from .generic import spe_zip, expand_list, isNumber, transpose_fill, flatten_list, isPolynom, isNumerand, postfix_op from .generic import spe_zip, isNumber, transpose_fill, flatten_list, isPolynom, postfix_op
from .render import txt, tex
from functools import wraps from functools import wraps
@ -15,7 +14,6 @@ def power_cache(fun):
@wraps(fun) @wraps(fun)
def cached_fun(self, power): def cached_fun(self, power):
#print("cache -> ", cache)
if (tuple(self._coef), power) in cache.keys(): if (tuple(self._coef), power) in cache.keys():
return cache[(tuple(self._coef), power)] return cache[(tuple(self._coef), power)]
else: else:
@ -346,8 +344,6 @@ class AbstractPolynom(Explicable):
with Expression.tmp_render(): with Expression.tmp_render():
coef_steps += list(coef_exp.simplify().explain()) coef_steps += list(coef_exp.simplify().explain())
#print('\t 1.coef_steps -> ', coef_steps)
else: else:
try: try:
with Expression.tmp_render(): with Expression.tmp_render():
@ -355,12 +351,9 @@ class AbstractPolynom(Explicable):
except AttributeError: except AttributeError:
coef_steps = [coef] coef_steps = [coef]
#print('\t 3.coef_steps -> ', coef_steps)
# On ajoute toutes ces étapes # On ajoute toutes ces étapes
coefs_steps.append(coef_steps) coefs_steps.append(coef_steps)
#print('\t coefs_steps -> ', coefs_steps)
# On retourne la matrice # On retourne la matrice
steps = [] steps = []
for coefs in transpose_fill(coefs_steps): for coefs in transpose_fill(coefs_steps):
@ -586,16 +579,6 @@ class AbstractPolynom(Explicable):
def __xor__(self, power): def __xor__(self, power):
return self.__pow__(power) return self.__pow__(power)
if __name__ == '__main__':
P = AbstractPolynom([[1, 2], [3, 4, 5], 6])
Q = P.reduce()
for i in Q.explain():
print(i)
#import doctest
# doctest.testmod()
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -88,8 +88,11 @@ class Explicable(Renderable):
""" """
self.steps = steps + self.steps self.steps = steps + self.steps
class Explicable_int(int, Explicable): class Explicable_int(int, Explicable):
""" An Explicable_int is an int which can be explain """ """ An Explicable_int is an int which can be explain """
isNumber = True isNumber = True
def __init__(self, val): def __init__(self, val):
@ -107,8 +110,11 @@ class Explicable_int(int, Explicable):
def __tex__(self): def __tex__(self):
return str(self._val) return str(self._val)
class Explicable_Decimal(Decimal, Explicable): class Explicable_Decimal(Decimal, Explicable):
""" An Explicable_Decimal is an decimal which can be explain """ """ An Explicable_Decimal is an decimal which can be explain """
isNumber = True isNumber = True
def __init__(self, val): def __init__(self, val):
@ -127,7 +133,6 @@ class Explicable_Decimal(Decimal, Explicable):
return str(self._val) return str(self._val)
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -2,9 +2,9 @@
# encoding: utf-8 # encoding: utf-8
# debuging # debuging
#from debug.tools import report # from debug.tools import report
from .generic import Stack, flatten_list, expand_list, isNumber, isOperator, isNumerand from .generic import flatten_list, expand_list, isOperator, isNumerand
from .str2tokens import str2tokens from .str2tokens import str2tokens
from .operator import op from .operator import op
from .explicable import Explicable, Explicable_int, Explicable_Decimal from .explicable import Explicable, Explicable_int, Explicable_Decimal
@ -14,6 +14,7 @@ from .random_expression import RdExpression
__all__ = ['Expression'] __all__ = ['Expression']
def pstf_factory(pstf_tokens): def pstf_factory(pstf_tokens):
"""Factory which tranform postfix tokens list into an Expression or the simpliest object type ready to be rendered """Factory which tranform postfix tokens list into an Expression or the simpliest object type ready to be rendered
@ -38,9 +39,7 @@ def pstf_factory(pstf_tokens):
< Fraction 1 / 2> < Fraction 1 / 2>
""" """
try: if len(pstf_tokens) == 1:
l_pstf_token = len(pstf_tokens)
except TypeError:
if isinstance(pstf_tokens[0], int): if isinstance(pstf_tokens[0], int):
return Explicable_int(pstf_tokens[0]) return Explicable_int(pstf_tokens[0])
elif isinstance(pstf_tokens[0], Decimal): elif isinstance(pstf_tokens[0], Decimal):
@ -49,23 +48,10 @@ def pstf_factory(pstf_tokens):
return Explicable_Decimal(Decimal(str(pstf_tokens[0]))) return Explicable_Decimal(Decimal(str(pstf_tokens[0])))
elif hasattr(pstf_tokens[0], 'STR_RENDER'): elif hasattr(pstf_tokens[0], 'STR_RENDER'):
return pstf_tokens[0] return pstf_tokens[0]
else:
return Expression(self)
else:
if l_pstf_token == 1:
if isinstance(pstf_tokens[0], int):
return Explicable_int(pstf_tokens[0])
elif isinstance(pstf_tokens[0], Decimal):
return Explicable_Decimal(pstf_tokens[0])
elif isinstance(pstf_tokens[0], float):
return Explicable_Decimal(Decimal(str(pstf_tokens[0])))
elif hasattr(pstf_tokens[0], 'STR_RENDER'):
return pstf_tokens[0]
else:
return Expression(self)
else:
return Expression(pstf_tokens) return Expression(pstf_tokens)
class Expression(Explicable): class Expression(Explicable):
"""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"""
@ -84,7 +70,6 @@ class Expression(Explicable):
@classmethod @classmethod
def tmp_render(cls, render=lambda _, x: pstf_factory(x)): def tmp_render(cls, render=lambda _, x: pstf_factory(x)):
# def tmp_render(cls, render=lambda _, x: Expression(x)):
""" Same ad tmp_render for Renderable but default render is Expression """ Same ad tmp_render for Renderable but default render is Expression
>>> exp = Expression("2*3/5") >>> exp = Expression("2*3/5")
@ -179,9 +164,9 @@ class Expression(Explicable):
try: try:
self.simplified = self.postfix_tokens[0].simplify() self.simplified = self.postfix_tokens[0].simplify()
except AttributeError: except AttributeError:
if isinstance(self.postfix_tokens[0],int): if isinstance(self.postfix_tokens[0], int):
self.simplified = Explicable_int(self.postfix_tokens[0]) self.simplified = Explicable_int(self.postfix_tokens[0])
elif isinstance(self.postfix_tokens[0],Decimal): elif isinstance(self.postfix_tokens[0], Decimal):
self.simplified = Explicable_Decimal(self.postfix_tokens[0]) self.simplified = Explicable_Decimal(self.postfix_tokens[0])
else: else:
self.simplified = self self.simplified = self
@ -411,36 +396,10 @@ class Expression(Explicable):
class ExpressionError(Exception): class ExpressionError(Exception):
pass pass
class ComputeError(Exception): class ComputeError(Exception):
pass pass
if __name__ == '__main__':
print('\n')
A = Expression("( -8 x + 8 ) ( -8 - ( -6 x ) )")
Ar = A.simplify()
for i in Ar.explain():
print(i)
# print("------------")
# for i in Ar.explain():
# print(i)
# print(type(Ar))
# print('\n-----------')
#A = Expression("-6 / 3 + 10 / -5")
#Ar = A.simplify()
# for i in Ar.explain():
# print(i)
# print('\n-----------')
#A = Expression("1/3 + 4/6")
#Ar = A.simplify()
# for i in Ar.explain():
# print(i)
#import doctest
# doctest.testmod()
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -6,7 +6,6 @@ from .generic import isNumber, postfix_op
from .operator import op from .operator import op
from .expression import Expression from .expression import Expression
from .explicable import Explicable from .explicable import Explicable
from .render import txt, tex
from copy import copy from copy import copy
@ -340,7 +339,7 @@ class Fraction(Explicable):
denom_s = [int(self._denom / gcd1), gcd1, op.mul] denom_s = [int(self._denom / gcd1), gcd1, op.mul]
steps.append(Expression(num_s + denom_s + [op.div])) steps.append(Expression(num_s + denom_s + [op.div]))
num = [self._num] + [int(other / gcd1), op.mul]* (int(other / gcd1) != 1) num = [self._num] + [int(other / gcd1), op.mul] * (int(other / gcd1) != 1)
denom = [int(self._denom / gcd1)] denom = [int(self._denom / gcd1)]
else: else:
num = [self._num, other, op.mul] num = [self._num, other, op.mul]
@ -379,7 +378,7 @@ class Fraction(Explicable):
num2 = [number._num] num2 = [number._num]
denom1 = [self._denom] denom1 = [self._denom]
steps.append(Expression(num1_s + num2_s + [op.mul] + \ steps.append(Expression(num1_s + num2_s + [op.mul] +
denom1_s + denom2_s + [op.mul, op.div])) denom1_s + denom2_s + [op.mul, op.div]))
exp = Expression(postfix_op(num1 + num2, op.mul, 1) + exp = Expression(postfix_op(num1 + num2, op.mul, 1) +
@ -527,74 +526,6 @@ class Fraction(Explicable):
return Fraction(self._num, self._denom) return Fraction(self._num, self._denom)
if __name__ == '__main__':
f = Fraction(1, 12)
g = Fraction(6, 12)
for i in g.simplify().explain():
print("g = ", i)
h = Fraction(1, -5)
t = Fraction(10, 3)
print("---------")
for i in (0 + h).explain():
print('0 + h = ', i)
# print("---------")
#print(str(f) , "+", str(t))
# for i in (f + t):
# print(i)
# print("---------")
#print(str(f) , "+", str(g))
# for i in (f + g):
# print(i)
# print("---------")
#print(str(f) , "-", str(g))
# for i in (f - g):
# print(i)
# print("---------")
#print(str(f) , "*", str(g))
# for i in (f * g):
# print(i)
# print("---------")
#print(str(h) , "+", str(t))
# for i in (h + t):
# print(i)
# print("---------")
#print(str(h) , "-", str(t))
# for i in (h - t):
# print(i)
# print("---------")
#print(str(h) , "*", str(t))
# for i in (h * t):
# print(i)
# print("---------")
#print("-", str(h) )
# for i in (-h):
# print(i)
# print("---------")
#print(str(h) , "/", str(t))
# for i in (h / t):
# print(i)
# print("---------")
#print(str(h) , "+", str(0))
# for i in (h + 0):
# print(i)
# print("---------")
#print(str(h) , "*", str(1))
# for i in (h * 1):
# print(i)
# print("---------")
#print(str(h) , "*", str(0))
# for i in (h * 0):
# print(i)
# print("---------")
#print(str(h) , "*", str(4))
# for i in (h * 4):
# print(i)
# print(f.simplify())
import doctest
doctest.testmod()
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -3,6 +3,7 @@
from .operator import Operator, save_mainOp from .operator import Operator, save_mainOp
class Add(Operator): class Add(Operator):
r""" The operator + r""" The operator +
@ -26,13 +27,13 @@ class Add(Operator):
""" """
_CARACT = { _CARACT = {
"operator" : "+", \ "operator": "+",
"name" : "add",\ "name": "add",
"priority" : 1, \ "priority": 1,
"arity" : 2, \ "arity": 2,
"actions" : ("__add__","__radd__"), \ "actions": ("__add__", "__radd__"),
"txt" : "{op1} + {op2}",\ "txt": "{op1} + {op2}",
"tex" : "{op1} + {op2}",\ "tex": "{op1} + {op2}",
} }
def __init__(self): def __init__(self):
@ -50,20 +51,19 @@ class Add(Operator):
if args[1][0] == "-": if args[1][0] == "-":
op1 = self.l_parenthesis(args[0], True) op1 = self.l_parenthesis(args[0], True)
op2 = self.r_parenthesis(args[1][1:], True) op2 = self.r_parenthesis(args[1][1:], True)
ans = link.replace('+','-').format(op1 = op1, op2 = op2) ans = link.replace('+', '-').format(op1=op1, op2=op2)
ans = save_mainOp(ans, self) ans = save_mainOp(ans, self)
return ans return ans
else: else:
op1 = self.l_parenthesis(args[0], True) op1 = self.l_parenthesis(args[0], True)
op2 = self.r_parenthesis(args[1], True) op2 = self.r_parenthesis(args[1], True)
ans = link.format(op1 = op1, op2 = op2) ans = link.format(op1=op1, op2=op2)
ans = save_mainOp(ans, self) ans = save_mainOp(ans, self)
return ans return ans
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -3,6 +3,7 @@
from .operator import Operator, save_mainOp from .operator import Operator, save_mainOp
class Div(Operator): class Div(Operator):
r""" The operator / r""" The operator /
@ -26,12 +27,12 @@ class Div(Operator):
""" """
_CARACT = { _CARACT = {
"operator" : "/", \ "operator": "/",
"name" : "div",\ "name": "div",
"priority" : 5, \ "priority": 5,
"arity" : 2, \ "arity": 2,
"txt" : "{op1} / {op2}",\ "txt": "{op1} / {op2}",
"tex" : "\\frac{{ {op1} }}{{ {op2} }}",\ "tex": "\\frac{{ {op1} }}{{ {op2} }}",
} }
def __init__(self): def __init__(self):
@ -43,11 +44,11 @@ class Div(Operator):
return op1 return op1
else: else:
from ..fraction import Fraction from ..fraction import Fraction
return Fraction(op1,op2) return Fraction(op1, op2)
def __tex__(self, *args): def __tex__(self, *args):
# Pas besoin de parenthèses en plus pour \frac # Pas besoin de parenthèses en plus pour \frac
replacement = {"op"+str(i+1): op for (i,op) in enumerate(args)} replacement = {"op"+str(i+1): op for (i, op) in enumerate(args)}
ans = self.tex.format(**replacement) ans = self.tex.format(**replacement)
ans = save_mainOp(ans, self) ans = save_mainOp(ans, self)

View File

@ -4,6 +4,7 @@
from .operator import Operator, save_mainOp from .operator import Operator, save_mainOp
class Mul(Operator): class Mul(Operator):
r""" The operator * r""" The operator *
@ -30,13 +31,13 @@ class Mul(Operator):
""" """
_CARACT = { _CARACT = {
"operator" : "*", \ "operator": "*",
"name" : "mul",\ "name": "mul",
"priority" : 4, \ "priority": 4,
"arity" : 2, \ "arity": 2,
"actions" : ("__mul__","__rmul__"), \ "actions": ("__mul__", "__rmul__"),
"txt" : "{op1} * {op2}",\ "txt": "{op1} * {op2}",
"tex" : "{op1} \\times {op2}",\ "tex": "{op1} \\times {op2}",
} }
def __init__(self): def __init__(self):
@ -106,17 +107,14 @@ class Mul(Operator):
op2 = self.r_parenthesis(args[1], True) op2 = self.r_parenthesis(args[1], True)
if not self.is_visible(op1, op2): if not self.is_visible(op1, op2):
ans = "{op1} {op2}".format(op1 = op1, op2 = op2) ans = "{op1} {op2}".format(op1=op1, op2=op2)
else: else:
ans = link.format(op1 = op1, op2 = op2) ans = link.format(op1=op1, op2=op2)
ans = save_mainOp(ans, self) ans = save_mainOp(ans, self)
return ans return ans
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -1,17 +1,16 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8 # encoding: utf-8
#from debug.tools import report # from debug.tools import report
from ..generic import flatten_list
from ..generic import flatten_list, isNumber
from functools import wraps
import types
class Operator(): class Operator():
"""The operator class, is a string (representation of the operator) with its arity""" """The operator class, is a string (representation of the operator) with its arity"""
def __init__(self, operator = "", name = "", priority = 0, actions = ("",""), txt = "", tex = "", arity = 2, **kwrds): def __init__(self, operator="", name="", priority=0, actions=("", ""), txt="", tex="", arity=2, **kwrds):
""" Create an Operator """ """ Create an Operator """
self.operator = operator self.operator = operator
self.name = name self.name = name
@ -29,8 +28,7 @@ class Operator():
return getattr(args[0], self.actions)() return getattr(args[0], self.actions)()
elif self.arity == 2: elif self.arity == 2:
#if type(args[1]) == int: if issubclass(type(args[1]), int):
if issubclass(type(args[1]),int):
return getattr(args[0], self.actions[0])(args[1]) return getattr(args[0], self.actions[0])(args[1])
else: else:
return getattr(args[1], self.actions[1])(args[0]) return getattr(args[1], self.actions[1])(args[0])
@ -45,12 +43,12 @@ class Operator():
""" """
if self.arity == 1: if self.arity == 1:
op1 = self.l_parenthesis(args[0], True) op1 = self.l_parenthesis(args[0], True)
ans = link.format(op1 = op1) ans = link.format(op1=op1)
elif self.arity == 2: elif self.arity == 2:
op1 = self.l_parenthesis(args[0], True) op1 = self.l_parenthesis(args[0], True)
op2 = self.r_parenthesis(args[1], True) op2 = self.r_parenthesis(args[1], True)
ans = link.format(op1 = op1, op2 = op2) ans = link.format(op1=op1, op2=op2)
ans = save_mainOp(ans, self) ans = save_mainOp(ans, self)
return ans return ans
@ -174,7 +172,7 @@ class Operator():
ans = opl ans = opl
elif opl.mainOp.priority < self.priority: elif opl.mainOp.priority < self.priority:
ans = flatten_list(["(", opl, ")"]) ans = flatten_list(["(", opl, ")"])
except AttributeError as e: except AttributeError:
# op has not the attribute priority # op has not the attribute priority
pass pass
@ -214,6 +212,7 @@ class Operator():
except AttributeError: except AttributeError:
return False return False
def save_mainOp(obj, mainOp): def save_mainOp(obj, mainOp):
"""Create a temporary class build over built-in type to stock the main operation of a calculus """Create a temporary class build over built-in type to stock the main operation of a calculus

View File

@ -2,7 +2,6 @@
# encoding: utf-8 # encoding: utf-8
import types
from .add import Add from .add import Add
from .div import Div from .div import Div
from .mul import Mul from .mul import Mul
@ -20,7 +19,7 @@ class Operator_set(object):
""" Initiate the operator_set """ """ Initiate the operator_set """
self._operators = {} self._operators = {}
def get_op(self, op, arity = 2): def get_op(self, op, arity=2):
r"""Return the corresponding operator r"""Return the corresponding operator
:op: symbole of the op :op: symbole of the op
@ -52,7 +51,7 @@ class Operator_set(object):
try: try:
return getattr(self, self._operators[(op, arity)]) return getattr(self, self._operators[(op, arity)])
except KeyError: except KeyError:
raise KeyError("{theOp} (arity: {arity}) is not available".format(theOp = op, arity = arity)) raise KeyError("{theOp} (arity: {arity}) is not available".format(theOp=op, arity=arity))
def available_op(self): def available_op(self):
""" Get the set of available operators strings """ Get the set of available operators strings
@ -72,8 +71,7 @@ class Operator_set(object):
return set([i[0] for i in self._operators]) return set([i[0] for i in self._operators])
def can_be_operator(cls, symbole): def can_be_operator(cls, symbole):
r""" r"""Tell if the symbole can be an operator
Tell if the symbole can be an operator
>>> op = Operator_set() >>> op = Operator_set()
>>> op.can_be_operator("+") >>> op.can_be_operator("+")

View File

@ -4,7 +4,6 @@
from .expression import Expression from .expression import Expression
from .operator import op from .operator import op
from .generic import isNumerand
from .random_expression import RdExpression from .random_expression import RdExpression
from .abstract_polynom import AbstractPolynom from .abstract_polynom import AbstractPolynom
@ -182,8 +181,6 @@ for name, func in inspect.getmembers(Polynom):
setattr(Polynom, name, polynom_factory(func)) setattr(Polynom, name, polynom_factory(func))
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -242,23 +242,6 @@ class Polynom_deg2(Polynom):
return "\\tkzTabVar{-/{}, +/{$" + str(beta) + "$}, -/{}}" return "\\tkzTabVar{-/{}, +/{$" + str(beta) + "$}, -/{}}"
if __name__ == '__main__':
#from .render import txt
# with Expression.tmp_render(txt):
# P = Polynom_deg2([2, 3, 4])
# print(P)
# print("\nDelta")
# for i in P.delta.explain():
# print(i)
# print("\nBeta")
# for i in P.beta.explain():
# print(i)
import doctest
doctest.testmod()
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -6,8 +6,6 @@ import re
import pyparsing import pyparsing
from .generic import flatten_list from .generic import flatten_list
from .arithmetic import gcd
def random_str(form, conditions=[], val_min=-10, val_max=10): def random_str(form, conditions=[], val_min=-10, val_max=10):
""" Create a random string using RdExpression class """ """ Create a random string using RdExpression class """
@ -41,9 +39,6 @@ class RdExpression(object):
:returns: set for elements which have to be replaced :returns: set for elements which have to be replaced
""" """
# pattern = "\{(.*?)\}" #select inside {} non greedy way
#varia_form = re.findall(pattern, self._form)
# TODO: Bug with varia with spaces |dim. nov. 23 10:44:34 CET 2014 # TODO: Bug with varia with spaces |dim. nov. 23 10:44:34 CET 2014
varia_form = flatten_list([eval(str(i[0])) for i in pyparsing.nestedExpr( varia_form = flatten_list([eval(str(i[0])) for i in pyparsing.nestedExpr(
'{', '}').searchString(self._form)]) '{', '}').searchString(self._form)])
@ -157,31 +152,6 @@ def desc_rdExp(rdExp):
print('') print('')
if __name__ == '__main__':
form = "({a};{b})"
cond = []
print(random_str(form, cond))
form = "{a+a*10}*4 + {a} + 2*{b}"
cond = [
"{a} + {b} in [1, 2, 3, 4, 5]",
"abs({a}) not in [1]",
"{b} not in [1]",
"gcd({a},{b}) == 1"]
print(random_str(form, cond))
form = "{a+a*10}*4 + {a} + 2*{b}"
cond = [
"{a-b} + {b} in list(range(20))",
"abs({a}) not in [1]",
"{b} not in [1]",
"gcd({a},{b}) == 1"]
print(random_str(form, cond))
import doctest
doctest.testmod()
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4:

View File

@ -56,6 +56,7 @@ def txt_render(token):
txt = Render(txt_render) txt = Render(txt_render)
def tex_render(token): def tex_render(token):
def render(*args): def render(*args):
try: try:
@ -65,6 +66,7 @@ def tex_render(token):
return render return render
tex = Render(tex_render) tex = Render(tex_render)
def p2i_render(token): def p2i_render(token):
def render(*args): def render(*args):
try: try:
@ -74,6 +76,7 @@ def p2i_render(token):
return render return render
p2i = Render(p2i_render) p2i = Render(p2i_render)
class Renderable(object): class Renderable(object):
""" """
A Renderable object is an object which can work with Render class. It means that it has to have attribute postfix_tokens. A Renderable object is an object which can work with Render class. It means that it has to have attribute postfix_tokens.

View File

@ -1,12 +1,12 @@
#!/usr/bin/env python #!/usr/bin/env python
# encoding: utf-8 # encoding: utf-8
from .generic import Stack, isOperator, isNumber, isPolynom from .generic import Stack, isNumber, isPolynom
from .operator import op from .operator import op
from decimal import Decimal from decimal import Decimal
import logging import logging
#logging.basicConfig(filename='str2tokens_debug.log',level=logging.DEBUG) # logging.basicConfig(filename='str2tokens_debug.log',level=logging.DEBUG)
def str2tokens(exp): def str2tokens(exp):
@ -70,6 +70,7 @@ def str2in_tokens(exp):
return tokens[2:] return tokens[2:]
def feed_digit(character, tok_b, tok_bb): def feed_digit(character, tok_b, tok_bb):
""" Feed token when a digit is detected """ Feed token when a digit is detected
@ -117,6 +118,7 @@ def feed_digit(character, tok_b, tok_bb):
else: else:
return [tok_b, int(character)] return [tok_b, int(character)]
def hidden_meaning_time(tok_b): def hidden_meaning_time(tok_b):
""" Return a "*" character if it is hidden meaning """ Return a "*" character if it is hidden meaning
@ -141,6 +143,7 @@ def hidden_meaning_time(tok_b):
return ["*"] return ["*"]
return [] return []
def feed_alpha(character): def feed_alpha(character):
""" Feed token when an alpha character is detected """ Feed token when an alpha character is detected
@ -152,6 +155,7 @@ def feed_alpha(character):
from pymath.calculus.polynom import Polynom from pymath.calculus.polynom import Polynom
return Polynom([0, 1], letter=character) return Polynom([0, 1], letter=character)
def feed_dot(tok_b): def feed_dot(tok_b):
r""" Build Decimal with the previous token r""" Build Decimal with the previous token
@ -202,7 +206,11 @@ def in2post_fix(infix_tokens):
for (pos_token, token) in enumerate(infix_tokens): for (pos_token, token) in enumerate(infix_tokens):
logging.debug(str(postfix_tokens)+ " | "+ str(opStack)+ " | "+ str(infix_tokens[(pos_token+1):])+ " | "+ str(arity_Stack)) logging.debug(str(postfix_tokens) +
" | " + str(opStack) +
" | " + str(infix_tokens[(pos_token+1):]) +
" | " + str(arity_Stack)
)
if token == ")": if token == ")":
next_op = opStack.pop() next_op = opStack.pop()
while next_op != op.par: while next_op != op.par:
@ -217,7 +225,7 @@ def in2post_fix(infix_tokens):
elif op.can_be_operator(token): elif op.can_be_operator(token):
if token == "(": if token == "(":
opStack.push(op.get_op(token,0)) opStack.push(op.get_op(token, 0))
# Set next arity counter # Set next arity counter
arity_Stack.push(0) arity_Stack.push(0)
else: else:
@ -232,19 +240,27 @@ def in2post_fix(infix_tokens):
postfix_tokens.append(next_op) postfix_tokens.append(next_op)
opStack.push(token_op) opStack.push(token_op)
logging.debug("--"+ token+ " -> "+ str(arity + 1)) logging.debug("--" + token + " -> " + str(arity + 1))
else: else:
postfix_tokens.append(token) postfix_tokens.append(token)
arity = arity_Stack.pop() arity = arity_Stack.pop()
arity_Stack.push(arity + 1) arity_Stack.push(arity + 1)
logging.debug(str(postfix_tokens)+ " | "+ str(opStack)+ " | "+ str(infix_tokens[(pos_token+1):])+ " | "+ str(arity_Stack)) logging.debug(str(postfix_tokens) +
" | " + str(opStack) +
" | " + str(infix_tokens[(pos_token+1):]) +
" | " + str(arity_Stack)
)
while not opStack.isEmpty(): while not opStack.isEmpty():
next_op = opStack.pop() next_op = opStack.pop()
postfix_tokens.append(next_op) postfix_tokens.append(next_op)
logging.debug(str(postfix_tokens)+ " | "+ str(opStack)+ " | "+ str(infix_tokens[(pos_token+1):])+ " | "+ str(arity_Stack)) logging.debug(str(postfix_tokens) +
" | " + str(opStack) +
" | " + str(infix_tokens[(pos_token+1):]) +
" | " + str(arity_Stack)
)
if arity_Stack.peek() != 1: if arity_Stack.peek() != 1:
raise ValueError( raise ValueError(
@ -255,29 +271,6 @@ def in2post_fix(infix_tokens):
return postfix_tokens return postfix_tokens
if __name__ == '__main__':
#a, s, m, d, p = Operator("+"), Operator("-"), Operator("*"), Operator("/"), Operator("^")
#in_tokens = str2in_tokens("2+3*4")
#print("\t in_tokens :" + str(in_tokens))
#
# print(in2post_fix(in_tokens))
#print(in2post_fix([op.par, 2, op.add, 5, op.sub, 1, ')', op.div, op.par, 3, op.mul, 4, ')']))
#print(in2post_fix([op.sub1, op.par, op.sub1, 2, ')']))
#print(in2post_fix([op.sub1, op.par, op.sub1, 2, op.add, 3, op.mul, 4, ')']))
print(str2tokens('2*3+4'))
print("\n------")
print(str2tokens('2x+4'))
print("\n------")
print(str2tokens('xx+4'))
print("\n------")
print(str2tokens('x(2+1)+4'))
print("\n------")
#import doctest
# doctest.testmod()
# ----------------------------- # -----------------------------
# Reglages pour 'vim' # Reglages pour 'vim'
# vim:set autoindent expandtab tabstop=4 shiftwidth=4: # vim:set autoindent expandtab tabstop=4 shiftwidth=4: