1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- class Stack:
- def __init__(self):
- self.items = []
-
- def isEmpty(self):
- return len(self.items)==0
-
- def push(self, item):
- self.items.append(item)
-
- def pop(self):
- return self.items.pop()
-
- def peek(self):
- if not self.isEmpty():
- return self.items[len(self.items)-1]
-
- def size(self):
- return len(self.items)
-
-
- def postfixEval(postfixExpr):
- operandStack = Stack()
- tokenList =postfixExpr.split()
-
- for token in tokenList:
- 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
-
- print(postfixEval('7 8 + 3 2 + /'))
|