WeCodeAcademy

Practice: Balanced Brackets

A famous stack problem: is every opening bracket closed in the right order? "(a[b]{c})" is balanced; "(]" and "(()" are not.

The idea: push each opening bracket on a stack. When you meet a closing bracket, the top of the stack must be its matching opener; pop it. At the end the stack must be empty.

Examplepython
Open in editor »
Quick check

At the end of a balanced check, what must be true of the stack?

Your turn: write the code

Write valid_parens(text) for round brackets only: return True if every ( has a matching ) in order. Print it for the three strings, one per line.

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.