Push every opening bracket, and pop when a closing one arrives. A stack checks nesting perfectly.
Python · intermediate · 7 min · 40 steps · free
def is_balanced(text):
pairs = {')': '(', ']': '[', '}': '{'}
stack = []
for ch in text:
if ch in '([{':
stack.append(ch)
elif ch in pairs:
if not stack or stack.pop() != pairs[ch]:
return False
return len(stack) == 0
print(is_balanced('{[()]}'))
print(is_balanced('(]'))is_balanced(). Its body does not run yet: it runs each time the function is called.is_balanced(), with text = '{[()]}'. It gets its own names.pairs is created and points to a new dict: {): '(', ]: '[', }: '{'}.stack is created and points to a new list: [].ch is created with the value '{'.ch in '([{' is true, so the block under it runs.{ goes on top of the stack.ch changes from '{' to '['.ch in '([{' is true, so the block under it runs.stack points to.ch changes from '[' to '('.ch in '([{' is true, so the block under it runs.{, [, (.ch changes from '(' to ')'.ch in '([{' is false, so the block under it is skipped.ch in pairs is true, so the block under it runs.) arrives: pop the top, (. It matches.ch changes from ')' to ']'.ch in '([{' is false, so the block under it is skipped.ch in pairs is true, so the block under it runs.stack points to.ch changes from ']' to '}'.ch in '([{' is false, so the block under it is skipped.ch in pairs is true, so the block under it runs.stack points to.for ch in text.is_balanced() has finished, so its names are gone. It prints True.is_balanced(), with text = '(]'. It gets its own names.pairs is created and points to a new dict: {): '(', ]: '[', }: '{'}.stack is created and points to a new list: [].ch is created with the value '('.ch in '([{' is true, so the block under it runs.stack points to.ch changes from '(' to ']'.ch in '([{' is false, so the block under it is skipped.ch in pairs is true, so the block under it runs.] arrives but the top is (: they do not match.False.is_balanced() has finished, so its names are gone. It prints False.Answer: 3
Answer: No, the stack is not empty at the end
← Reversing a Linked List · Queues →