Stack Evaluates Reverse Polish Notation

Postfix expressions evaluate with one stack: push numbers, pop two operands per operator, and the final remainder is the whole expression's value.

PythonData Integrity

Code

pythonsnippet
24 lines
def evaluate(tokens: list[str]) -> int:
    stack: list[int] = []
    operators = {"+", "-", "*", "/"}
    for token in tokens:
        if token in operators:
            right = stack.pop()
            left = stack.pop()
            if token == "+":
                stack.append(left + right)
            elif token == "-":
                stack.append(left - right)
            elif token == "*":
                stack.append(left * right)
            else:
                # postfix division truncates toward zero
                stack.append(int(left / right))
        else:
            stack.append(int(token))
    return stack.pop()


print(evaluate(["2", "3", "+"]))                                # 2 + 3
print(evaluate(["5", "1", "2", "+", "4", "*", "+", "3", "-"]))   # 5 + (1 + 2) * 4 - 3
print(evaluate(["7", "2", "/"]))                                # truncating division

Output

Captured from a sandboxed run of this snippet in the build pipeline.

5
14
3

What the run performs

Stack Evaluates Reverse Polish Notation keeps everything in the function evaluate.

Iteration happens inside for token in tokens — everything outside it runs once.

Caveats

  • Every API in play comes with the platform, so nothing has to be installed.

Applying it

This file revolves around the signature: def evaluate(tokens: list[str]) -> int

Import evaluate from the file and call it — the rest of the code is implementation detail.

Statements that matter

elif token == "-":
    stack.append(left - right)
elif token == "*":
    stack.append(left * right)

Interactive Tools for This Topic

FAQ

Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `evaluate` at load time.