Day 16

A Stack-Based RPN Calculator in Python

Try it!

Enter expressions in Reverse Polish Notation (postfix). Operands go first, operator last. Examples: 3 4 + → 7, 5 1 2 + 4 * + 3 - → 14. Type quit to exit.



Description


A Python calculator that evaluates expressions written in Reverse Polish Notation (RPN), also called postfix notation. Instead of writing 3 + 4, you write 3 4 + — operands come before the operator. The implementation uses a stack: numbers are pushed onto it as they're read, and each operator pops two values, computes the result, and pushes it back. RPN eliminates the need for parentheses and operator precedence rules entirely, and is the evaluation model used internally by most compilers and interpreters. A clean illustration of how a stack turns a seemingly tricky parsing problem into a simple linear scan.

View the source code


def evaluate_rpn(expression):
    stack = []
    tokens = expression.split()
    operators = {
        '+': lambda a, b: a + b,
        '-': lambda a, b: a - b,
        '*': lambda a, b: a * b,
        '/': lambda a, b: a / b,
    }
    for token in tokens:
        if token in operators:
            b = stack.pop()
            a = stack.pop()
            if token == '/' and b == 0:
                return None, "Error: division by zero."
            stack.append(operators[token](a, b))
        else:
            stack.append(float(token))
    result = stack[0]
    return (int(result) if result == int(result) else result), None

while True:
    expr = input("> ").strip()
    if expr.lower() == "quit": break
    result, error = evaluate_rpn(expr)
    print(error if error else f"= {result}")

Previous Day
Next Day