diff --git a/pymath/calculus/abstract_polynom.py b/pymath/calculus/abstract_polynom.py index 06a3b0f..efdc1ab 100644 --- a/pymath/calculus/abstract_polynom.py +++ b/pymath/calculus/abstract_polynom.py @@ -4,8 +4,7 @@ from .explicable import Explicable from .expression import Expression from .operator import op -from .generic import spe_zip, expand_list, isNumber, transpose_fill, flatten_list, isPolynom, isNumerand, postfix_op -from .render import txt, tex +from .generic import spe_zip, isNumber, transpose_fill, flatten_list, isPolynom, postfix_op from functools import wraps @@ -15,7 +14,6 @@ def power_cache(fun): @wraps(fun) def cached_fun(self, power): - #print("cache -> ", cache) if (tuple(self._coef), power) in cache.keys(): return cache[(tuple(self._coef), power)] else: @@ -346,8 +344,6 @@ class AbstractPolynom(Explicable): with Expression.tmp_render(): coef_steps += list(coef_exp.simplify().explain()) - #print('\t 1.coef_steps -> ', coef_steps) - else: try: with Expression.tmp_render(): @@ -355,12 +351,9 @@ class AbstractPolynom(Explicable): except AttributeError: coef_steps = [coef] - #print('\t 3.coef_steps -> ', coef_steps) # On ajoute toutes ces étapes coefs_steps.append(coef_steps) - #print('\t coefs_steps -> ', coefs_steps) - # On retourne la matrice steps = [] for coefs in transpose_fill(coefs_steps): @@ -586,16 +579,6 @@ class AbstractPolynom(Explicable): def __xor__(self, 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' # vim:set autoindent expandtab tabstop=4 shiftwidth=4: diff --git a/pymath/calculus/explicable.py b/pymath/calculus/explicable.py index dd9adcc..3bb69af 100644 --- a/pymath/calculus/explicable.py +++ b/pymath/calculus/explicable.py @@ -33,7 +33,7 @@ class Explicable(Renderable): 2 + 10 \times 4 2 + 40 42 - + """ old_s = '' # les étapes pour l'atteindre @@ -88,8 +88,11 @@ class Explicable(Renderable): """ self.steps = steps + self.steps + class Explicable_int(int, Explicable): + """ An Explicable_int is an int which can be explain """ + isNumber = True def __init__(self, val): @@ -107,8 +110,11 @@ class Explicable_int(int, Explicable): def __tex__(self): return str(self._val) + class Explicable_Decimal(Decimal, Explicable): + """ An Explicable_Decimal is an decimal which can be explain """ + isNumber = True def __init__(self, val): @@ -127,7 +133,6 @@ class Explicable_Decimal(Decimal, Explicable): return str(self._val) - # ----------------------------- # Reglages pour 'vim' # vim:set autoindent expandtab tabstop=4 shiftwidth=4: diff --git a/pymath/calculus/expression.py b/pymath/calculus/expression.py index 68c3743..1e2b317 100644 --- a/pymath/calculus/expression.py +++ b/pymath/calculus/expression.py @@ -2,9 +2,9 @@ # encoding: utf-8 # 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 .operator import op from .explicable import Explicable, Explicable_int, Explicable_Decimal @@ -14,6 +14,7 @@ from .random_expression import RdExpression __all__ = ['Expression'] + def pstf_factory(pstf_tokens): """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> """ - try: - l_pstf_token = len(pstf_tokens) - except TypeError: + if len(pstf_tokens) == 1: if isinstance(pstf_tokens[0], int): return Explicable_int(pstf_tokens[0]) elif isinstance(pstf_tokens[0], Decimal): @@ -49,22 +48,9 @@ def pstf_factory(pstf_tokens): return Explicable_Decimal(Decimal(str(pstf_tokens[0]))) elif hasattr(pstf_tokens[0], 'STR_RENDER'): 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): """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 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 >>> exp = Expression("2*3/5") @@ -179,9 +164,9 @@ class Expression(Explicable): try: self.simplified = self.postfix_tokens[0].simplify() except AttributeError: - if isinstance(self.postfix_tokens[0],int): + if isinstance(self.postfix_tokens[0], int): 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]) else: self.simplified = self @@ -411,36 +396,10 @@ class Expression(Explicable): class ExpressionError(Exception): pass + class ComputeError(Exception): 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' # vim:set autoindent expandtab tabstop=4 shiftwidth=4: diff --git a/pymath/calculus/fraction.py b/pymath/calculus/fraction.py index 46d7cbb..10abc6b 100644 --- a/pymath/calculus/fraction.py +++ b/pymath/calculus/fraction.py @@ -6,7 +6,6 @@ from .generic import isNumber, postfix_op from .operator import op from .expression import Expression from .explicable import Explicable -from .render import txt, tex from copy import copy @@ -329,7 +328,7 @@ class Fraction(Explicable): if other == 0: exp = Expression([0]) elif other == 1: - exp = copy(self) + exp = copy(self) elif isinstance(other, int): gcd1 = gcd(other, self._denom) @@ -340,7 +339,7 @@ class Fraction(Explicable): denom_s = [int(self._denom / gcd1), gcd1, op.mul] 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)] else: num = [self._num, other, op.mul] @@ -379,8 +378,8 @@ class Fraction(Explicable): num2 = [number._num] denom1 = [self._denom] - steps.append(Expression(num1_s + num2_s + [op.mul] + \ - denom1_s + denom2_s + [op.mul, op.div])) + steps.append(Expression(num1_s + num2_s + [op.mul] + + denom1_s + denom2_s + [op.mul, op.div])) exp = Expression(postfix_op(num1 + num2, op.mul, 1) + postfix_op(denom1 + denom2, op.mul, 1) + @@ -527,74 +526,6 @@ class Fraction(Explicable): 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' # vim:set autoindent expandtab tabstop=4 shiftwidth=4: diff --git a/pymath/calculus/operator/add.py b/pymath/calculus/operator/add.py index ba861c8..1d9a40a 100644 --- a/pymath/calculus/operator/add.py +++ b/pymath/calculus/operator/add.py @@ -3,6 +3,7 @@ from .operator import Operator, save_mainOp + class Add(Operator): r""" The operator + @@ -26,13 +27,13 @@ class Add(Operator): """ _CARACT = { - "operator" : "+", \ - "name" : "add",\ - "priority" : 1, \ - "arity" : 2, \ - "actions" : ("__add__","__radd__"), \ - "txt" : "{op1} + {op2}",\ - "tex" : "{op1} + {op2}",\ + "operator": "+", + "name": "add", + "priority": 1, + "arity": 2, + "actions": ("__add__", "__radd__"), + "txt": "{op1} + {op2}", + "tex": "{op1} + {op2}", } def __init__(self): @@ -50,20 +51,19 @@ class Add(Operator): if args[1][0] == "-": op1 = self.l_parenthesis(args[0], 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) return ans else: op1 = self.l_parenthesis(args[0], 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) return ans - # ----------------------------- # Reglages pour 'vim' # vim:set autoindent expandtab tabstop=4 shiftwidth=4: diff --git a/pymath/calculus/operator/div.py b/pymath/calculus/operator/div.py index 9b661c9..de04956 100644 --- a/pymath/calculus/operator/div.py +++ b/pymath/calculus/operator/div.py @@ -3,6 +3,7 @@ from .operator import Operator, save_mainOp + class Div(Operator): r""" The operator / @@ -26,12 +27,12 @@ class Div(Operator): """ _CARACT = { - "operator" : "/", \ - "name" : "div",\ - "priority" : 5, \ - "arity" : 2, \ - "txt" : "{op1} / {op2}",\ - "tex" : "\\frac{{ {op1} }}{{ {op2} }}",\ + "operator": "/", + "name": "div", + "priority": 5, + "arity": 2, + "txt": "{op1} / {op2}", + "tex": "\\frac{{ {op1} }}{{ {op2} }}", } def __init__(self): @@ -43,11 +44,11 @@ class Div(Operator): return op1 else: from ..fraction import Fraction - return Fraction(op1,op2) + return Fraction(op1, op2) def __tex__(self, *args): # 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 = save_mainOp(ans, self) diff --git a/pymath/calculus/operator/mul.py b/pymath/calculus/operator/mul.py index d9bd6c1..4df886b 100644 --- a/pymath/calculus/operator/mul.py +++ b/pymath/calculus/operator/mul.py @@ -4,6 +4,7 @@ from .operator import Operator, save_mainOp + class Mul(Operator): r""" The operator * @@ -30,13 +31,13 @@ class Mul(Operator): """ _CARACT = { - "operator" : "*", \ - "name" : "mul",\ - "priority" : 4, \ - "arity" : 2, \ - "actions" : ("__mul__","__rmul__"), \ - "txt" : "{op1} * {op2}",\ - "tex" : "{op1} \\times {op2}",\ + "operator": "*", + "name": "mul", + "priority": 4, + "arity": 2, + "actions": ("__mul__", "__rmul__"), + "txt": "{op1} * {op2}", + "tex": "{op1} \\times {op2}", } def __init__(self): @@ -106,17 +107,14 @@ class Mul(Operator): op2 = self.r_parenthesis(args[1], True) if not self.is_visible(op1, op2): - ans = "{op1} {op2}".format(op1 = op1, op2 = op2) + ans = "{op1} {op2}".format(op1=op1, op2=op2) else: - ans = link.format(op1 = op1, op2 = op2) + ans = link.format(op1=op1, op2=op2) ans = save_mainOp(ans, self) return ans - - - # ----------------------------- # Reglages pour 'vim' # vim:set autoindent expandtab tabstop=4 shiftwidth=4: diff --git a/pymath/calculus/operator/operator.py b/pymath/calculus/operator/operator.py index 8c8bd75..b3e4e61 100644 --- a/pymath/calculus/operator/operator.py +++ b/pymath/calculus/operator/operator.py @@ -1,17 +1,16 @@ #!/usr/bin/env python # 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(): """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 """ self.operator = operator self.name = name @@ -29,8 +28,7 @@ class Operator(): return getattr(args[0], self.actions)() 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]) else: return getattr(args[1], self.actions[1])(args[0]) @@ -45,12 +43,12 @@ class Operator(): """ if self.arity == 1: op1 = self.l_parenthesis(args[0], True) - ans = link.format(op1 = op1) + ans = link.format(op1=op1) elif self.arity == 2: op1 = self.l_parenthesis(args[0], 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) return ans @@ -174,7 +172,7 @@ class Operator(): ans = opl elif opl.mainOp.priority < self.priority: ans = flatten_list(["(", opl, ")"]) - except AttributeError as e: + except AttributeError: # op has not the attribute priority pass @@ -214,6 +212,7 @@ class Operator(): except AttributeError: return False + def save_mainOp(obj, mainOp): """Create a temporary class build over built-in type to stock the main operation of a calculus diff --git a/pymath/calculus/operator/operator_set.py b/pymath/calculus/operator/operator_set.py index 38af650..300251e 100644 --- a/pymath/calculus/operator/operator_set.py +++ b/pymath/calculus/operator/operator_set.py @@ -2,7 +2,6 @@ # encoding: utf-8 -import types from .add import Add from .div import Div from .mul import Mul @@ -20,7 +19,7 @@ class Operator_set(object): """ Initiate the operator_set """ self._operators = {} - def get_op(self, op, arity = 2): + def get_op(self, op, arity=2): r"""Return the corresponding operator :op: symbole of the op @@ -31,7 +30,7 @@ class Operator_set(object): >>> op.get_op('+') + >>> mul = op.get_op('*') - Traceback (most recent call last): + Traceback (most recent call last): ... KeyError: '* (arity: 2) is not available' >>> op.store_operator(Mul()) @@ -42,7 +41,7 @@ class Operator_set(object): '{op1} * {op2}' >>> op.store_operator(Sub1()) >>> sub1 = op.get_op('-') - Traceback (most recent call last): + Traceback (most recent call last): ... KeyError: '- (arity: 2) is not available' >>> sub1 = op.get_op('-', 1) @@ -52,7 +51,7 @@ class Operator_set(object): try: return getattr(self, self._operators[(op, arity)]) 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): """ Get the set of available operators strings @@ -72,8 +71,7 @@ class Operator_set(object): return set([i[0] for i in self._operators]) def can_be_operator(cls, symbole): - r""" - Tell if the symbole can be an operator + r"""Tell if the symbole can be an operator >>> op = Operator_set() >>> op.can_be_operator("+") @@ -81,7 +79,7 @@ class Operator_set(object): >>> op.store_operator(Add()) >>> op.can_be_operator("+") True - + """ if type(symbole) == str: return symbole in [i[0] for i in cls._operators] @@ -89,7 +87,7 @@ class Operator_set(object): return False def store_operator(self, operator): - """ Save the operator as a method and + """ Save the operator as a method and :param operator: the operator (the class) (it will be accessible through .name method name. @@ -105,7 +103,7 @@ class Operator_set(object): >>> a.tex '{op1} + {op2}' >>> op.store_operator("+") - Traceback (most recent call last): + Traceback (most recent call last): ... ValueError: + is not en Operator it's a """ diff --git a/pymath/calculus/polynom.py b/pymath/calculus/polynom.py index 12b7fa1..1e0ca33 100644 --- a/pymath/calculus/polynom.py +++ b/pymath/calculus/polynom.py @@ -4,7 +4,6 @@ from .expression import Expression from .operator import op -from .generic import isNumerand from .random_expression import RdExpression from .abstract_polynom import AbstractPolynom @@ -182,8 +181,6 @@ for name, func in inspect.getmembers(Polynom): setattr(Polynom, name, polynom_factory(func)) - - # ----------------------------- # Reglages pour 'vim' # vim:set autoindent expandtab tabstop=4 shiftwidth=4: diff --git a/pymath/calculus/polynomDeg2.py b/pymath/calculus/polynomDeg2.py index 076eb25..873c263 100644 --- a/pymath/calculus/polynomDeg2.py +++ b/pymath/calculus/polynomDeg2.py @@ -242,23 +242,6 @@ class Polynom_deg2(Polynom): 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' # vim:set autoindent expandtab tabstop=4 shiftwidth=4: diff --git a/pymath/calculus/random_expression.py b/pymath/calculus/random_expression.py index 82d5c45..f4c7849 100644 --- a/pymath/calculus/random_expression.py +++ b/pymath/calculus/random_expression.py @@ -6,8 +6,6 @@ import re import pyparsing from .generic import flatten_list -from .arithmetic import gcd - def random_str(form, conditions=[], val_min=-10, val_max=10): """ Create a random string using RdExpression class """ @@ -41,9 +39,6 @@ class RdExpression(object): :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 varia_form = flatten_list([eval(str(i[0])) for i in pyparsing.nestedExpr( '{', '}').searchString(self._form)]) @@ -157,31 +152,6 @@ def desc_rdExp(rdExp): 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' # vim:set autoindent expandtab tabstop=4 shiftwidth=4: diff --git a/pymath/calculus/render.py b/pymath/calculus/render.py index 1babded..70459b6 100644 --- a/pymath/calculus/render.py +++ b/pymath/calculus/render.py @@ -56,6 +56,7 @@ def txt_render(token): txt = Render(txt_render) + def tex_render(token): def render(*args): try: @@ -65,6 +66,7 @@ def tex_render(token): return render tex = Render(tex_render) + def p2i_render(token): def render(*args): try: @@ -74,6 +76,7 @@ def p2i_render(token): return render p2i = Render(p2i_render) + 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. diff --git a/pymath/calculus/str2tokens.py b/pymath/calculus/str2tokens.py index 747dafa..7e997d3 100644 --- a/pymath/calculus/str2tokens.py +++ b/pymath/calculus/str2tokens.py @@ -1,12 +1,12 @@ #!/usr/bin/env python # encoding: utf-8 -from .generic import Stack, isOperator, isNumber, isPolynom +from .generic import Stack, isNumber, isPolynom from .operator import op from decimal import Decimal import logging -#logging.basicConfig(filename='str2tokens_debug.log',level=logging.DEBUG) +# logging.basicConfig(filename='str2tokens_debug.log',level=logging.DEBUG) def str2tokens(exp): @@ -46,7 +46,7 @@ def str2in_tokens(exp): for character in exp: if character.isdigit(): - tokens += feed_digit(character, tokens.pop(), tokens[-1]) + tokens += feed_digit(character, tokens.pop(), tokens[-1]) elif character == "(": tokens += hidden_meaning_time(tokens[-1]) @@ -70,6 +70,7 @@ def str2in_tokens(exp): return tokens[2:] + def feed_digit(character, tok_b, tok_bb): """ Feed token when a digit is detected @@ -117,6 +118,7 @@ def feed_digit(character, tok_b, tok_bb): else: return [tok_b, int(character)] + def hidden_meaning_time(tok_b): """ Return a "*" character if it is hidden meaning @@ -141,6 +143,7 @@ def hidden_meaning_time(tok_b): return ["*"] return [] + def feed_alpha(character): """ Feed token when an alpha character is detected @@ -152,6 +155,7 @@ def feed_alpha(character): from pymath.calculus.polynom import Polynom return Polynom([0, 1], letter=character) + def feed_dot(tok_b): r""" Build Decimal with the previous token @@ -202,7 +206,11 @@ def in2post_fix(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 == ")": next_op = opStack.pop() while next_op != op.par: @@ -217,7 +225,7 @@ def in2post_fix(infix_tokens): elif op.can_be_operator(token): if token == "(": - opStack.push(op.get_op(token,0)) + opStack.push(op.get_op(token, 0)) # Set next arity counter arity_Stack.push(0) else: @@ -232,19 +240,27 @@ def in2post_fix(infix_tokens): postfix_tokens.append(next_op) opStack.push(token_op) - logging.debug("--"+ token+ " -> "+ str(arity + 1)) + logging.debug("--" + token + " -> " + str(arity + 1)) else: postfix_tokens.append(token) arity = arity_Stack.pop() 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(): next_op = opStack.pop() 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: raise ValueError( @@ -255,29 +271,6 @@ def in2post_fix(infix_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' # vim:set autoindent expandtab tabstop=4 shiftwidth=4: