diff --git a/calculus.py b/calculus.py index b76c887..1b2551f 100644 --- a/calculus.py +++ b/calculus.py @@ -71,6 +71,47 @@ def computePostfix(postfixExp): return operandeStack.pop() +def computePostfixBis(postfixExp): + """Compute a postfix expression like a good student + + :param postfixExp: a postfix expression + :returns: the result of the expression + + """ + print(postfixToInfix(postfixExp)) + # where to save numbers or + operandeStack = Stack() + + tokenList = postfixExp.split(" ") + + while len(tokenList) > 1: + tmpTokenList = [] + i = 0 + while len(tokenList) > 2: + if (tokenList[1].isdigit() or (tokenList[1][0] == "-" and tokenList[1][1:].isdigit())) and tokenList[2] in "+-*/": + # S'il y a une opération à faire + op1 = tokenList[0] + op2 = tokenList[1] + token = tokenList[2] + res = doMath(token, op1, op2) + + tmpTokenList.append(res) + # Comme on vient de faire le calcul, on peut sauter les deux prochains termes + i += 3 + + del tokenList[0:3] + else: + tmpTokenList.append(tokenList[0]) + i += 1 + + del tokenList[0] + tmpTokenList += tokenList + + tokenList = tmpTokenList.copy() + print(postfixToInfix(" ".join(tokenList))) + + return tokenList[0] + def doMath(op, op1, op2): """Compute "op1 op op2" @@ -132,6 +173,8 @@ def test(exp): postfix = infixToPostfix(exp) print("Postfix " , postfix) print(computePostfix(postfix)) + print("Bis") + print(computePostfixBis(postfix)) #print(postfixToInfix(postfix)) diff --git a/generic.py b/generic.py index 875b500..f515871 100644 --- a/generic.py +++ b/generic.py @@ -9,6 +9,14 @@ class Stack(object): """@todo: to be defined1 """ self.items = [] + def pushFromList(self, list): + """Push the list in the stack + + :param list: a list + """ + for i in list[::-1]: + self.push(i) + def isEmpty(self): """ Says if the stack is empty :returns: @todo @@ -27,27 +35,24 @@ class Stack(object): def pop(self): """Getting the last item and remove it - :returns: @todo + :returns: last item """ return self.items.pop() - def peek(self): + def peek(self, posi = 0): """Getting the last item - :returns: @todo + :param posi: which item to peek 0 (last) 1 (the onebefore the last)... + :returns: the item """ - return self.items[-1] + return self.items[-1 - posi] - def size(self): - """Lenght of the stack - :returns: @todo - - """ + def __len__(self): return len(self.items) def __str__(self): - return str(self.items) + return str(self.items) + " -> " def __add__(self, addList): return self.items + addList