Advanced · Stacks and queues · 201 of 264
Balanced brackets
Check that every bracket (), [] and {} is closed by the right kind in the right order. Use a stack (a list with append and pop). Other characters are ignored.
Input: one line. Output: balanced or not balanced
Examples
Input
{[()()]}Output
balanced
Input
([)]
Output
not balanced
Input
((
Output
not balanced
Input
print(a[0])
Output
balanced
2 more tests check other inputs when you press Check.
Stuck? The idea behind stacks and queues
A stack is last in, first out: a list's append() and pop(). A queue is first in, first out: collections.deque with append() and popleft().
Stacks match brackets and undo actions; queues serve things in the order they came.
stack = []
for ch in "(()":
if ch == "(":
stack.append(ch)
elif stack:
stack.pop()
print("left open:", len(stack))Watch for: pop() on an empty list stops the program: check the stack isn't empty first.