Balanced Brackets Stack Matching
Push openers on a stack and require each closer to mirror the stack top, so crossed pairs, stray closers, and unclosed openers all fail loudly.
Code
PAIRS = {")": "(", "]": "[", "}": "{"}
def is_balanced(text):
"""Match brackets with a stack; closers must mirror the latest opener."""
stack = []
for char in text:
if char in "([{":
stack.append(char)
elif char in PAIRS:
if not stack or stack.pop() != PAIRS[char]:
return False
return not stack # leftovers mean unclosed openers
samples = ["{[()()]}", "([)]", "(((", "{a[b]c}", ")(", "code(x)[y]{z}"]
for sample in samples:
print(f"{sample!r} -> {is_balanced(sample)}")Output
Captured from a sandboxed run of this snippet in the build pipeline.
'{[()()]}' -> True
'([)]' -> False
'(((' -> False
'{a[b]c}' -> True
')(' -> False
'code(x)[y]{z}' -> TrueWalkthrough
The active pieces are the function is_balanced.
A single loop drives the file — for char in text.
Watch out for
- Zero packages pulled in — the runtime ships every API this code touches.
Using it
What the code exposes: def is_balanced(text)
Import is_balanced from the file and call it — the rest of the code is implementation detail.
Key statements
elif char in PAIRS:
if not stack or stack.pop() != PAIRS[char]:
return False
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Bracket BalancerCheck whether parentheses, square brackets, and braces are balanced, reporting mismatches and maximum nesting depth.
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. The file defines `is_balanced` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.