5/36
Part 1 of 8 · Last in, first outLearn and do

Push each opener, and each closer must match the top

Counting brackets can't see their order

The obvious check counts each kind and compares the counts:

from collections import Counter


def balanced_by_count(text):
    counts = Counter(text)
    return all(counts[o] == counts[c] for o, c in ("()", "[]", "{}"))


for text in ["f(a[0], {k: v})", "([)]", "())(", "(("]:
    print(f"{text:16} {balanced_by_count(text)}")
f(a[0], {k: v})  True
([)]             True
())(             True
((               False

Only the first one is balanced. Counts can't see order. In ([)] the ) arrives while [ is the bracket still waiting to close. In ())( the second ) arrives with nothing open.

A stack sees both problems. Push each opener. When a closer comes, the top of the stack must be its partner, and you pop it:

Reading "{[]()}", one character at a time
{
read {push
{[
read [push
{
read ]pop [
{(
read (push
{
read )pop (
emptyread }pop {

The stack ends empty, so every opener was closed.

Predict

Push each opener, and each closer must match the top. What happens on ([)]?

Pick an answer above to see the rest