In: Computer Science
Implement in Python using stack operations.
Postfix Calculator
Post fix calculator
• We use a stack
• When an operand is read, push it on statck
• When an operator is read i.e +, *. /, -
– Pop two from the top of the stack and apply the operator and push
the result on stack
if there is one value instead of two display an error message
• Keep repeating until an equal sign, = is read; pop from the top
of stack and stop.
Postfix Expression Result
4 5 7 2 + - * = -16 ===> (5 - (7 + 2 ) )* 4 = -16
3 4 + 2 * 7 / = 2
5 7 + 6 2 - * = 48
4 2 3 5 1 - + * + = 18 ===> (5-1 + 3 ) * 2 + 4 = 18
List as Stack
"""
File: pyStackPostfix.py
Author: JD
"""
# 5 7 + 6 2 - * = 48
print("Postfix Calculator\n")
stack = [] # Empty stack
y = int(0)
z = int(0)
w = int(0)
while True:
x = input("Enter a postfix expression one by one:")
if x >= '0' and x<= '9':
x = int(x)
stack.append(x) # Push on top of stack
elif x == '+': # Got an operator
if len(stack) >= 2:
y = stack.pop() # Pop from top of stack
z = stack.pop()
w = y + z
stack.append(w) # Push result back
else:
print("Stack error") # Not enough operhand A + B
break
elif x == '-':
if len(stack) >= 2:
y = stack.pop()
z = stack.pop()
w = y - z
stack.append(w)
else:
print("Stack error")
break
elif x == '*':
if len(stack) >= 2:
y = stack.pop()
z = stack.pop()
w = y * z
stack.append(w)
else:
print("Stack error")
break
elif x == '/':
if len(stack) >= 2:
y = stack.pop()
z = stack.pop()
w = y / z
stack.append(w)
else:
print("Stack error")
break
elif x == '=': # Equal operator
if len(stack) == 1:
z = stack.pop() # Pop the result
print (z)
break
else:
print("Stack error")
break
IN PYTON
You just need to change the order of opertors in operations, i.e use z - y instead of y - z. Also you can input full experssion in one line.
"""
File: pyStackPostfix.py
Author: JD
"""
# 5 7 + 6 2 - * = 48
print("Postfix Calculator\n")
stack = [] # Empty stack
y = int(0)
z = int(0)
w = int(0)
# expression list
exp = input("Enter a postfix expression:").split()
for x in exp:
if x >= '0' and x<= '9':
x = int(x)
stack.append(x) # Push on top of stack
elif x == '+': # Got an operator
if len(stack) >= 2:
y = stack.pop() # Pop from top of stack
z = stack.pop()
w = z + y
stack.append(w) # Push result back
else:
print("Stack error") # Not enough operhand A + B
break
elif x == '-':
if len(stack) >= 2:
y = stack.pop()
z = stack.pop()
w = z - y
stack.append(w)
else:
print("Stack error")
break
elif x == '*':
if len(stack) >= 2:
y = stack.pop()
z = stack.pop()
w = z * y
stack.append(w)
else:
print("Stack error")
break
elif x == '/':
if len(stack) >= 2:
y = stack.pop()
z = stack.pop()
w = z / y
stack.append(w)
else:
print("Stack error")
break
elif x == '=': # Equal operator
if len(stack) == 1:
z = stack.pop() # Pop the result
print(z)
break
else:
print("Stack error")
break