{"record":{"id":"6470001f2328e4e8","repo":"TheAlgorithms/Python","slug":"invalid-expression","errorCode":null,"errorMessage":"invalid expression","messagePattern":"invalid expression","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"data_structures/stacks/infix_to_prefix_conversion.py","lineNumber":114,"sourceCode":"                post_fix.append(stack.pop())  # Pop stack & add the content to Postfix\n            stack.pop()\n        elif len(stack) == 0:\n            stack.append(x)  # If stack is empty, push x to stack\n        else:  # while priority of x is not > priority of element in the stack\n            while stack and stack[-1] != \"(\" and priority[x] <= priority[stack[-1]]:\n                post_fix.append(stack.pop())  # pop stack & add to Postfix\n            stack.append(x)  # push x to stack\n\n        print(\n            x.center(8),\n            (\"\".join(stack)).ljust(print_width),\n            (\"\".join(post_fix)).ljust(print_width),\n            sep=\" | \",\n        )  # Output in tabular format\n\n    while len(stack) > 0:  # while stack is not empty\n        if stack[-1] == \"(\":  # open bracket with no close bracket\n            raise ValueError(\"invalid expression\")\n\n        post_fix.append(stack.pop())  # pop stack & add to Postfix\n        print(\n            \" \".center(8),\n            (\"\".join(stack)).ljust(print_width),\n            (\"\".join(post_fix)).ljust(print_width),\n            sep=\" | \",\n        )  # Output in tabular format\n\n    return \"\".join(post_fix)  # return Postfix as str\n\n\ndef infix_2_prefix(infix: str) -> str:\n    \"\"\"\n    >>> infix_2_prefix(\"a+b^c\")  # doctest: +NORMALIZE_WHITESPACE\n     Symbol  |  Stack  | Postfix\n    ----------------------------\n       c     |         | c","sourceCodeStart":96,"sourceCodeEnd":132,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/stacks/infix_to_prefix_conversion.py#L96-L132","documentation":"Raised at the end of infix_to_postfix() in data_structures/stacks/infix_to_prefix_conversion.py:114 when, after consuming the whole expression, an unclosed '(' remains on the operator stack. It is the mirror of the empty-stack ')' error: this one detects an open bracket that never got closed.","triggerScenarios":"Expressions like '(1+2' or '((3+4)*5' — any input where a '(' is pushed and never popped by a matching ')'. All remaining operators are popped in the final while loop, but a '(' left on stack aborts with this error.","commonSituations":"Truncated expressions from files or user input; like the sibling IndexError, this converter performs no up-front balance check.","solutions":["Pre-check with balanced_parentheses(expr) and reject early","Fix the expression so every '(' has a closing ')'","Catch ValueError around the call when input cannot be trusted"],"exampleFix":"// before\nresult = infix_to_postfix('(1+2')  # ValueError: invalid expression\n\n# after\nassert expr.count('(') == expr.count(')') and balanced_parentheses(expr)\nresult = infix_to_postfix(expr)","handlingStrategy":"validation","validationCode":"if expr.count('(') != expr.count(')') or not balanced_parentheses(expr):\n    raise ValueError('unbalanced expression')\nresult = infix_to_postfix(expr)","typeGuard":null,"tryCatchPattern":"try:\n    result = infix_to_postfix(expr)\nexcept ValueError as e:\n    if str(e) != 'invalid expression':\n        raise\n    # unclosed '(' — reject input","preventionTips":["Count '(' vs ')' as a cheap first-pass check before full validation","Log the raw expression when this fires; truncation is the usual root cause"],"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"}