Challenge: Postfix Calculator
Completed
In postfix notation the operator comes after its two numbers: 3 4 + means 3 + 4, and 5 1 2 + 4 * + 3 - means 5 + (1 + 2) × 4 − 3. Evaluate a postfix expression with a stack. Division / is whole-number division (round down, like //).
Input
One line: numbers and operators + - * / separated by spaces.
Output
The result.
Example
Input
3 4 +
Output
7
Editor
Python
Hints
Numbers go on the stack.
For an operator, pop b first, then a, and push a (op) b.
Solution explanation
Order matters for − and /: the first number popped is the right side.
Show solution
stack = []
for tok in input().split():
if tok in "+-*/":
b = stack.pop()
a = stack.pop()
if tok == "+":
stack.append(a + b)
elif tok == "-":
stack.append(a - b)
elif tok == "*":
stack.append(a * b)
else:
stack.append(a // b)
else:
stack.append(int(tok))
print(stack[0]) Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module