A bracket validator uses a stack of expected closing tokens to check properly nested bracket sequences.
Python bracket stack: reject mismatches at the first invalid close
Operation contract
The import expression parser pushes the matching closer for every opener. A closer must match the top expectation; a mismatched closer or a leftover opener makes the expression invalid. The fixture accepts only bracket characters and caps input length, so ordinary text cannot be silently ignored as though it were parsed.
Failure and ownership boundary
This is bracket validation, not a Python parser. Quoted strings, comments and expression semantics require a grammar that knows whether a bracket is actually syntax. Python strings and bytes: reject decoding errors before parsing records defines an earlier layer, while Java stack algorithm: validate nested delimiters checks the same nesting invariant.
Working program
def balanced_brackets(text):
if len(text) > 4096:
raise ValueError("expression too long")
closing = {"(": ")", "[": "]", "{": "}"}
expected = []
for token in text:
if token in closing:
expected.append(closing[token])
elif token in ")]}":
if not expected or expected.pop() != token:
return False
else:
raise ValueError("brackets only")
return not expected
print(balanced_brackets("{[()]}"))
print(balanced_brackets("([)]"))
print(balanced_brackets("(("))Output
True
False
FalseCosts and limits
For n bracket tokens the scan is O(n) time and worst-case O(n) stack storage. Early mismatch can stop before consuming every token.
Common Mistakes
- Validate the top expectation rather than only counting tokens.
- A bracket checker is not a source-language parser.
Connected lessons
Python lists: slicing copies the outer sequence, not nested objects, Python strings and bytes: reject decoding errors before parsing records, Java stack algorithm: validate nested delimiters.
