Advanced · Stacks and queues · 202 of 264
Postfix calculator
Evaluate an expression in postfix notation (operators after their numbers), e.g. 3 4 + 2 * means (3 + 4) * 2. Use a stack. Division is whole division (//).
Input: numbers and operators + - * // separated by spaces. Output: the value.
Examples
Input
3 4 + 2 *
Output
14
Input
5
Output
5
Input
10 2 8 * + 3 -
Output
23
One more test checks other inputs when you press Check.
Stuck? The idea behind stacks and queues
A stack is last in, first out: a list's append() and pop(). A queue is first in, first out: collections.deque with append() and popleft().
Stacks match brackets and undo actions; queues serve things in the order they came.
stack = []
for ch in "(()":
if ch == "(":
stack.append(ch)
elif stack:
stack.pop()
print("left open:", len(stack))Watch for: pop() on an empty list stops the program: check the stack isn't empty first.