PythiloEasy · 15 min · Task 2 of 20 · progress kept in this browser

Balanced brackets

A text is balanced if every closing bracket matches the most recent bracket still open. Three kinds appear: (), [] and {}. All other characters are ignored.

is_balanced("(a[b]{c})")  # True
is_balanced("([)]")       # False
is_balanced("(")          # False

Counting each kind is not enough, because ([)] has matching counts but crosses over. What you need is the most recently opened bracket, which is exactly what a stack gives you.

A Python list works as a stack: append pushes and pop removes the last item, both in constant time.

stack = []
stack.append("(")
print(stack.pop())  # (

Two failure cases are easy to forget: a closing bracket when the stack is empty, and items left on the stack at the end.

Your task

Write is_balanced(text) returning True when all (), [] and {} in the text are properly matched and nested.