TheAlgorithms/Python · error · ValueError

Mismatched parentheses

Error message

Mismatched parentheses

What it means

Raised by infix_to_postfix() in data_structures/stacks/infix_to_postfix_conversion.py:67 as a precondition check: the expression is first passed to balanced_parentheses(), and any imbalance (unclosed '(' or stray ')') is rejected before conversion begins. This is deliberate fail-fast validation rather than a mid-parse crash.

Source

Thrown at data_structures/stacks/infix_to_postfix_conversion.py:67

        ...
    ValueError: Mismatched parentheses
    >>> infix_to_postfix("")
    ''
    >>> infix_to_postfix("3+2")
    '3 2 +'
    >>> infix_to_postfix("(3+4)*5-6")
    '3 4 + 5 * 6 -'
    >>> infix_to_postfix("(1+2)*3/4-5")
    '1 2 + 3 * 4 / 5 -'
    >>> infix_to_postfix("a+b*c+(d*e+f)*g")
    'a b c * + d e * f + g * +'
    >>> infix_to_postfix("x^y/(5*z)+2")
    'x y ^ 5 z * / 2 +'
    >>> infix_to_postfix("2^3^2")
    '2 3 2 ^ ^'
    """
    if not balanced_parentheses(expression_str):
        raise ValueError("Mismatched parentheses")
    stack: Stack[str] = Stack()
    postfix = []
    for char in expression_str:
        if char.isalpha() or char.isdigit():
            postfix.append(char)
        elif char == "(":
            stack.push(char)
        elif char == ")":
            while not stack.is_empty() and stack.peek() != "(":
                postfix.append(stack.pop())
            stack.pop()
        else:
            while True:
                if stack.is_empty():
                    stack.push(char)
                    break

                char_precedence = precedence(char)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Run balanced_parentheses(expression) yourself first and reject/report before converting
  2. Fix the expression: ensure every '(' has a matching ')' in correct order
  3. Catch ValueError at the input-parsing boundary and surface it to the user as invalid input

Example fix

// before
postfix = infix_to_postfix(user_expr)  # ValueError('(1+2')

# after
from data_structures.stacks.infix_to_postfix_conversion import balanced_parentheses
if not balanced_parentheses(user_expr):
    raise InputError('unbalanced parentheses in expression')
postfix = infix_to_postfix(user_expr)
Defensive patterns

Strategy: validation

Validate before calling

from data_structures.stacks.infix_to_postfix_conversion import balanced_parentheses
if not balanced_parentheses(expr):
    raise ValueError(f'unbalanced parentheses: {expr!r}')
postfix = infix_to_postfix(expr)

Type guard

def is_balanced(expr: str) -> bool:
    depth = 0
    for ch in expr:
        if ch == '(':
            depth += 1
        elif ch == ')':
            depth -= 1
            if depth < 0:
                return False
    return depth == 0

Try / catch

try:
    postfix = infix_to_postfix(expr)
except ValueError as e:
    if 'Mismatched parentheses' not in str(e):
        raise
    return None  # or re-prompt user

Prevention

When it happens

Trigger: infix_to_postfix(')3+4('), infix_to_postfix('(1+2'), or any string where open and close parentheses do not nest correctly. Whitespace and operator errors do not trigger it — only the parentheses check does.

Common situations: User-supplied or file-read expressions with typos, truncated input lines, or expressions containing characters the caller assumed would be validated later.

Related errors


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