1. 程式人生 > >用棧實現計算器

用棧實現計算器

class Stack:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        return self.items.pop()

    def peek(self):
        return self.items[len(self.items)-1]

    def 
size(self): return len(self.items) def infixToPostfix(infixexpr): ''' 中綴轉字尾 :param infixexpr: :return: ''' prec = {} prec['*'] = 3 prec['/'] = 3 prec['+'] = 2 prec['-'] = 2 prec['('] = 1 opStack = Stack() postfixList = [] # tokenList = infixexpr.split() # print(tokenList)
for token in infixexpr: if token in '0123456789': postfixList.append(token) elif token == '(': opStack.push(token) elif token == ')': topToken = opStack.pop() while topToken != '(': postfixList.append(topToken) topToken = opStack.pop() else
: while (not opStack.isEmpty()) and \ (prec[opStack.peek()] >= prec[token]): print(opStack) postfixList.append(opStack.pop()) opStack.push(token) while not opStack.isEmpty(): postfixList.append(opStack.pop()) return ''.join(postfixList) def postfixEval(postfixExpr): operandStack = Stack() # tokenList = postfixExpr.split() for token in postfixExpr: if token in '0123456789': operandStack.push(int(token)) else: operand2 = operandStack.pop() operand1 = operandStack.pop() result = doMath(token, operand1, operand2) operandStack.push(result) return operandStack.pop() def doMath(op, op1, op2): if op == '*': return op1 * op2 elif op == '/': return op1 / op2 elif op == '+': return op1 + op2 else: return op1 - op2