Evaluate an expression written in postfix order

Stacks and queues Mid-level Python 3.13+ Reviewed By Best Latest Apps

Predict the output

What does this print?

Python 3.13
print(-7 // 2, int(-7 / 2), 7 // 2)

Options

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A -4 -3 3

Right: floor division rounds down; int() of the float truncates toward zero.

The two rules only disagree for negative results, which is exactly where the question's 'toward zero' rule matters.

Why not the others?
  • B -3 -3 3. Floor division rounds toward negative infinity, giving -4.
  • C -4 -4 3. int(-3.5) truncates toward zero, giving -3.

30-second answer

Scan the tokens with a stack of numbers. A number is pushed. An operator pops the right operand, then the left, applies the operation and pushes the result. At the end the stack holds exactly one number: the answer. O(n) time and space.

Practise saying it · 30 s. No recording, just a timer

Explain postfix evaluation with a stack.

Say your answer out loud, then check which of these points you covered:

  • Push numbers
  • Operator pops right then left
  • Truncate toward zero

Deep dive

Order matters for - and /: the first pop is the right operand.

Truncating toward zero in Python needs int(a / b) or sign handling; // rounds down, which differs for negative results.

Postfix needs no brackets or precedence rules, which is why stack machines and some calculators use it.

Python solution Ran on Python 3.13.5 · mypy --strict
Python 3.13
def eval_postfix(tokens: list[str]) -> int:
    nums: list[int] = []
    for tok in tokens:
        if tok in ("+", "-", "*", "/"):
            right, left = nums.pop(), nums.pop()
            if tok == "+":
                nums.append(left + right)
            elif tok == "-":
                nums.append(left - right)
            elif tok == "*":
                nums.append(left * right)
            else:
                q = abs(left) // abs(right)
                nums.append(q if (left < 0) == (right < 0) else -q)
        else:
            nums.append(int(tok))
    return nums[0]

Common mistakes

  • Using // for division and getting -4 instead of -3 for -7 / 2.
  • Popping operands in the wrong order.

Senior take & follow-ups

Call out the truncation rule and how you handle it in Python.

Follow-up questions

Think of your answer first, then open the hint.

  1. How would you evaluate normal infix expressions?

    Show hint

    Shunting-yard to convert to postfix, or two stacks for numbers and operators.

  2. How do you avoid float rounding in the division?

    Show hint

    Divide absolute values with // and fix the sign.

What each operation costs: Stack · Queue · Deque

From the author

DSA Master - Data & Algorithms

Free on iPhone and iPad: watch 50+ data structures and algorithms step through animations, run the code in the playground, and try the daily challenge.

Suggest a fix if something here is wrong or out of date.