How to Evaluate RPN Expressions in Python
Use a stack to evaluate Reverse Polish Notation token lists with a dictionary of operator lambdas, truncating division toward zero.
Python code
22 linesdef eval_rpn(tokens):
stack = []
ops = {
'+': lambda a, b: a + b,
'-': lambda a, b: a - b,
'*': lambda a, b: a * b,
'/': lambda a, b: int(a / b) # truncate toward zero
}
for token in tokens:
if token in ops:
b = stack.pop()
a = stack.pop()
stack.append(ops[token](a, b))
else:
stack.append(int(token))
return stack[0]
if __name__ == "__main__":
# Example: "3 4 + 2 * 7 /" → ((3+4)*2)/7 = 2
expression = ["3", "4", "+", "2", "*", "7", "/"]
result = eval_rpn(expression)
print(f"Result of {expression} = {result}")
Output
Result of ['3', '4', '+', '2', '*', '7', '/'] = 2
How it works
A stack holds operands as tokens are scanned; when an operator appears, the top two values are popped and the result is pushed. The ops dictionary maps each operator symbol to a lambda that computes the result, and integer division uses int(a / b) for Python-style truncation like many calculators. This approach gives O(n) time and O(n) space. At the end, the single remaining stack value is the expression's result.
Common mistakes
- Forgetting that operand order matters: the first popped value is `b`, not `a`
- Using `//` for division, which floors toward negative infinity instead of truncating toward zero
- Not converting string tokens to `int` before pushing them
- Assuming division returns a float when truncation toward zero is expected
Variations
- Swap the lambda for a `match` statement in Python 3.10+
- Use a list-based stack with a helper function for each operator instead of lambdas
Real-world use cases
- Implementing calculators and expression parsers in trading platforms that need deterministic operator ordering.
- Building custom scripting engines where user input is pre-tokenized into postfix notation for simple evaluation.
- Evaluating formula strings in spreadsheet-like tools that convert input to RPN to avoid precedence bugs.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.