Match brackets with a stack
The most recently opened bracket must close first. That last-in, first-out order is exactly what a stack gives you: push every opener, and every closer must match the top.
stack = []
for char in "([])":
print(char, stack)Think before coding
A closer is wrong when the stack is empty or its top is a different kind. At the end, anything still on the stack was never closed. Other characters are ignored, so the same check works on code or formulas. Work through the example by hand before changing the starter. Decide what should happen for an empty input, a single value and a repeated value where those cases apply. The checks use several inputs so a hard-coded answer cannot stand in for the rule.
Your task
Write balanced(text) returning True when every (, [ and { is closed by its own kind in the right order. Ignore all other characters.
The explanation opens here once every check passes.