Balanced brackets
Task
Write is_balanced(s) that returns True if every ( [ { in the string is closed by the matching bracket in the right order, and False otherwise. Ignore all other characters.
Python 3.14 running in your browser (Pyodide). Standard library only. print() output is shown below the results.
Tests
| Call | Expected |
|---|---|
is_balanced('(a[b]{c})') | True |
is_balanced('([)]') | False |
is_balanced('((') | False |
is_balanced('') | True |
is_balanced('}{') | False |
is_balanced('f(x[0]) + {k: v}') | True |
- Counting brackets is not enough:
([)]has matching counts but bad nesting. - Push opening brackets on a stack; on a closing bracket, the top of the stack must be its partner.
Show solution
Python
def is_balanced(s):
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in s:
if ch in '([{':
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return not stackA stack remembers the order brackets were opened, so each closing bracket can be checked against the most recent unclosed one.
Why this works
A stack remembers the order brackets were opened, so each closing bracket can be checked against the most recent unclosed one.
Revise in the Python guide, or test yourself with the Python practice sets.