TheAlgorithms/Python · error · ArithmeticError

Input is not a valid postfix expression

Error message

Input is not a valid postfix expression

What it means

Raised by evaluate() in data_structures/stacks/postfix_evaluation.py:186 as a final sanity check: after processing every token, the operand stack must hold exactly one value (the result). Any other size means the token sequence was not a well-formed postfix expression — typically too many operands (e.g. ['1','2','3','+']) or consecutive operators with insufficient operands would have already failed during popping.

Source

Thrown at data_structures/stacks/postfix_evaluation.py:186

                "".rjust(8),
                f"pop({a})".ljust(12),
                stack,
                sep=" | ",
            )
        # evaluate the 2 values popped from stack & push result to stack
        stack.append(OPERATORS[x](a, b))  # type: ignore[index]
        if verbose:
            # output in tabular format
            print(
                f"{x}".rjust(8),
                f"push({a}{x}{b})".ljust(12),
                stack,
                sep=" | ",
            )
    # If everything is executed correctly, the stack will contain
    # only one element which is the result
    if len(stack) != 1:
        raise ArithmeticError("Input is not a valid postfix expression")
    return float(stack[0])


if __name__ == "__main__":
    # Create a loop so that the user can evaluate postfix expressions multiple times
    while True:
        expression = input("Enter a Postfix Expression (space separated): ").split(" ")
        prompt = "Do you want to see stack contents while evaluating? [y/N]: "
        verbose = input(prompt).strip().lower() == "y"
        output = evaluate(expression, verbose)
        print("Result = ", output)
        prompt = "Do you want to enter another expression? [y/N]: "
        if input(prompt).strip().lower() != "y":
            break

View on GitHub (pinned to f5988cc097)

Solutions

  1. Validate the shape before calling: len(tokens) >= 1 and operand count == operator count + 1, and every running prefix has operands > operators
  2. Fix the upstream expression/converter so it emits balanced postfix
  3. Catch ArithmeticError to reject malformed expressions at the boundary

Example fix

// before
result = evaluate(['1', '2', '3', '+'])  # ArithmeticError: stack ends with [1, 5]

# after
def is_valid_postfix(tokens):
    depth = 0
    for t in tokens:
        depth += -1 if t in OPERATORS else 1
        if depth <= 0 and t in OPERATORS: return False
    return depth == 1
result = evaluate(tokens) if is_valid_postfix(tokens) else None
Defensive patterns

Strategy: validation

Validate before calling

from data_structures.stacks.postfix_evaluation import OPERATORS

def is_valid_postfix(tokens) -> bool:
    depth = 0
    for t in tokens:
        if t in OPERATORS:
            if depth < 2:
                return False  # operator without two operands on stack
            depth -= 1
        else:
            depth += 1
    return depth == 1

Try / catch

try:
    result = evaluate(tokens)
except ArithmeticError as e:
    if str(e) != 'Input is not a valid postfix expression':
        raise
    result = None  # malformed: operand/operator counts mismatched

Prevention

When it happens

Trigger: evaluate(['1','2']) leaves two items on the stack; evaluate(['1','2','3','+']) leaves two; an operator-heavy list like ['+','1'] fails earlier on stack.pop(). Any operand count != operator count + 1 in valid arrangement triggers it.

Common situations: Hand-written postfix strings, conversion bugs in an infix->postfix step feeding evaluate(), or user input that omitted an operator.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/ed8ebbb06fb8239c. Report an issue: GitHub.