Balanced delimiters with a stack

Problem

Implement is_balanced(text) for (), [], and {}. Ignore non-delimiter characters.

Starter code

def is_balanced(text):
    pass
Reveal answer or reference solution
def is_balanced(text):
    pairs = {')': '(', ']': '[', '}': '{'}
    stack = []
    for ch in text:
        if ch in '([{':
            stack.append(ch)
        elif ch in pairs:
            if not stack or stack.pop() != pairs[ch]:
                return False
    return not stack

Public tests

  • is_balanced('a[(b+c)*{d-e}]')True
  • is_balanced('([)]')False
  • is_balanced('(()')False

Local history

Loading attempts saved in this browser…

Use with your agent

Share this URL and your attempt. Ask the agent to start with a clarifying question or the smallest useful hint.

Tutor me on https://mlprep.iwase.dev/programming/diagnostic/original-py-balanced/. If window.mlPrepAgent is available, read attempts for item original-py-balanced before tutoring. Inspect my attempt, keep the item ID, and do not reveal the full answer first. After a real attempt, append its record and read it back.

Appears in