TheAlgorithms/Python · error · ValueError
invalid expression
Error message
invalid expression
What it means
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.
Source
Thrown at data_structures/stacks/infix_to_prefix_conversion.py:114
post_fix.append(stack.pop()) # Pop stack & add the content to Postfix
stack.pop()
elif len(stack) == 0:
stack.append(x) # If stack is empty, push x to stack
else: # while priority of x is not > priority of element in the stack
while stack and stack[-1] != "(" and priority[x] <= priority[stack[-1]]:
post_fix.append(stack.pop()) # pop stack & add to Postfix
stack.append(x) # push x to stack
print(
x.center(8),
("".join(stack)).ljust(print_width),
("".join(post_fix)).ljust(print_width),
sep=" | ",
) # Output in tabular format
while len(stack) > 0: # while stack is not empty
if stack[-1] == "(": # open bracket with no close bracket
raise ValueError("invalid expression")
post_fix.append(stack.pop()) # pop stack & add to Postfix
print(
" ".center(8),
("".join(stack)).ljust(print_width),
("".join(post_fix)).ljust(print_width),
sep=" | ",
) # Output in tabular format
return "".join(post_fix) # return Postfix as str
def infix_2_prefix(infix: str) -> str:
"""
>>> infix_2_prefix("a+b^c") # doctest: +NORMALIZE_WHITESPACE
Symbol | Stack | Postfix
----------------------------
c | | cView on GitHub (pinned to f5988cc097)
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
Example fix
// before
result = infix_to_postfix('(1+2') # ValueError: invalid expression
# after
assert expr.count('(') == expr.count(')') and balanced_parentheses(expr)
result = infix_to_postfix(expr) Defensive patterns
Strategy: validation
Validate before calling
if expr.count('(') != expr.count(')') or not balanced_parentheses(expr):
raise ValueError('unbalanced expression')
result = infix_to_postfix(expr) Try / catch
try:
result = infix_to_postfix(expr)
except ValueError as e:
if str(e) != 'invalid expression':
raise
# unclosed '(' — reject input Prevention
- Count '(' vs ')' as a cheap first-pass check before full validation
- Log the raw expression when this fires; truncation is the usual root cause
When it happens
Trigger: 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.
Common situations: Truncated expressions from files or user input; like the sibling IndexError, this converter performs no up-front balance check.
Related errors
- Mismatched parentheses
- list index out of range
- {token} is neither a number nor a valid operator
- number must be positive
- The value of input must be non-negative
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/6470001f2328e4e8.
Report an issue: GitHub.