← Stacks & Queues

Drill #19 — Evaluate postfix expression

Easy Operand Stack Stacks & Queues

In plain English: Calculate the result of a math expression written in postfix notation like '2 1 + 3 *'.

Postfix notation eliminates the need for parentheses and precedence — operands are always ready on the stack when an operator appears.

Prompt

Evaluate a postfix (reverse Polish notation) expression.

Try to write it from scratch before scrolling down.

Solution

def eval_postfix(tokens):
    stack = []
    ops = {'+': lambda a,b: a+b, '-': lambda a,b: a-b,
           '*': lambda a,b: a*b, '/': lambda a,b: int(a/b)}
    for t in tokens:
        if t in ops:
            b, a = stack.pop(), stack.pop()  # pop order matters: b first, then a
            stack.append(ops[t](a, b))
        else:
            stack.append(int(t))
    return stack[0]

# Test: eval_postfix(["2","1","+","3","*"]) == 9
O(n) time · O(n) space

Related Micro Drills

← Drill #18 Drill #20 →