{"record":{"id":"6db40e549667f9b0","repo":"TheAlgorithms/Python","slug":"mismatched-parentheses","errorCode":null,"errorMessage":"Mismatched parentheses","messagePattern":"Mismatched parentheses","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"data_structures/stacks/infix_to_postfix_conversion.py","lineNumber":67,"sourceCode":"        ...\n    ValueError: Mismatched parentheses\n    >>> infix_to_postfix(\"\")\n    ''\n    >>> infix_to_postfix(\"3+2\")\n    '3 2 +'\n    >>> infix_to_postfix(\"(3+4)*5-6\")\n    '3 4 + 5 * 6 -'\n    >>> infix_to_postfix(\"(1+2)*3/4-5\")\n    '1 2 + 3 * 4 / 5 -'\n    >>> infix_to_postfix(\"a+b*c+(d*e+f)*g\")\n    'a b c * + d e * f + g * +'\n    >>> infix_to_postfix(\"x^y/(5*z)+2\")\n    'x y ^ 5 z * / 2 +'\n    >>> infix_to_postfix(\"2^3^2\")\n    '2 3 2 ^ ^'\n    \"\"\"\n    if not balanced_parentheses(expression_str):\n        raise ValueError(\"Mismatched parentheses\")\n    stack: Stack[str] = Stack()\n    postfix = []\n    for char in expression_str:\n        if char.isalpha() or char.isdigit():\n            postfix.append(char)\n        elif char == \"(\":\n            stack.push(char)\n        elif char == \")\":\n            while not stack.is_empty() and stack.peek() != \"(\":\n                postfix.append(stack.pop())\n            stack.pop()\n        else:\n            while True:\n                if stack.is_empty():\n                    stack.push(char)\n                    break\n\n                char_precedence = precedence(char)","sourceCodeStart":49,"sourceCodeEnd":85,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/stacks/infix_to_postfix_conversion.py#L49-L85","documentation":"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.","triggerScenarios":"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.","commonSituations":"User-supplied or file-read expressions with typos, truncated input lines, or expressions containing characters the caller assumed would be validated later.","solutions":["Run balanced_parentheses(expression) yourself first and reject/report before converting","Fix the expression: ensure every '(' has a matching ')' in correct order","Catch ValueError at the input-parsing boundary and surface it to the user as invalid input"],"exampleFix":"// before\npostfix = infix_to_postfix(user_expr)  # ValueError('(1+2')\n\n# after\nfrom data_structures.stacks.infix_to_postfix_conversion import balanced_parentheses\nif not balanced_parentheses(user_expr):\n    raise InputError('unbalanced parentheses in expression')\npostfix = infix_to_postfix(user_expr)","handlingStrategy":"validation","validationCode":"from data_structures.stacks.infix_to_postfix_conversion import balanced_parentheses\nif not balanced_parentheses(expr):\n    raise ValueError(f'unbalanced parentheses: {expr!r}')\npostfix = infix_to_postfix(expr)","typeGuard":"def is_balanced(expr: str) -> bool:\n    depth = 0\n    for ch in expr:\n        if ch == '(':\n            depth += 1\n        elif ch == ')':\n            depth -= 1\n            if depth < 0:\n                return False\n    return depth == 0","tryCatchPattern":"try:\n    postfix = infix_to_postfix(expr)\nexcept ValueError as e:\n    if 'Mismatched parentheses' not in str(e):\n        raise\n    return None  # or re-prompt user","preventionTips":["Validate parentheses before conversion, not after","When reading expressions from files, watch for truncation at line boundaries"],"tags":["stack","expression-parsing","validation","python"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}