|
@@ -0,0 +1,46 @@
|
|
1
|
+class Stack:
|
|
2
|
+ def __init__(self):
|
|
3
|
+ self.items = []
|
|
4
|
+
|
|
5
|
+ def isEmpty(self):
|
|
6
|
+ return len(self.items)==0
|
|
7
|
+
|
|
8
|
+ def push(self, item):
|
|
9
|
+ self.items.append(item)
|
|
10
|
+
|
|
11
|
+ def pop(self):
|
|
12
|
+ return self.items.pop()
|
|
13
|
+
|
|
14
|
+ def peek(self):
|
|
15
|
+ if not self.isEmpty():
|
|
16
|
+ return self.items[len(self.items)-1]
|
|
17
|
+
|
|
18
|
+ def size(self):
|
|
19
|
+ return len(self.items)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+def postfixEval(postfixExpr):
|
|
23
|
+ operandStack = Stack()
|
|
24
|
+ tokenList =postfixExpr.split()
|
|
25
|
+
|
|
26
|
+ for token in tokenList:
|
|
27
|
+ if token in"0123456789":
|
|
28
|
+ operandStack.push(int(token))
|
|
29
|
+ else:
|
|
30
|
+ operand2 =operandStack.pop()
|
|
31
|
+ operand1 =operandStack.pop()
|
|
32
|
+ result =doMath(token,operand1,operand2)
|
|
33
|
+ operandStack.push(result)
|
|
34
|
+ return operandStack.pop()
|
|
35
|
+
|
|
36
|
+def doMath(op, op1, op2):
|
|
37
|
+ if op == "*":
|
|
38
|
+ return op1 * op2
|
|
39
|
+ elif op == "/":
|
|
40
|
+ return op1 / op2
|
|
41
|
+ elif op == "+":
|
|
42
|
+ return op1 + op2
|
|
43
|
+ else:
|
|
44
|
+ return op1 - op2
|
|
45
|
+
|
|
46
|
+print(postfixEval('7 8 + 3 2 + /'))
|