-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpostfix.py
More file actions
61 lines (45 loc) · 1.35 KB
/
Copy pathpostfix.py
File metadata and controls
61 lines (45 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Stack (object):
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 calcPostfix(postfixexp):
stack = Stack()
tokenlist = postfixexp.split()
print(tokenlist)
for token in tokenlist:
if token in "+*-/":
op2 = stack.pop()
op1 = stack.pop()
if token == "+":
result = op2 + op1
stack.push(result)
print (stack.items)
elif token == "-":
result = op2 - op1
stack.push(result)
print (stack.items)
elif token == "*":
result = op2 * op1
stack.push(result)
print (stack.items)
else:
result = op2 / op1
stack.push(result)
print (stack.items)
else:
stack.push(int(token))
print (stack.items)
return stack.peek()
def main():
a = "1 2 3 4 * + +"
print(calcPostfix(a))
main()