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.

PythonData Integrity

Code

pythonsnippet
16 lines
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}' -> True

Walkthrough

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

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.