A stack is useful whenever the newest unfinished thing must be handled first. The top stores the next piece of work to finish.
Opening symbols create unfinished work
When we see an opening bracket, push it. When we see a closing bracket, it must match the latest opening bracket on top.
- Push begins or saves work.
- Pop finishes the newest work.
- Peek checks the top without removing it.
- An empty stack means nothing is waiting.
Order is the important rule
def balanced(text):
stack = []
pairs = {")": "(", "]": "[", "}": "{"}
for character in text:
if character in "([{":
stack.append(character)
elif character in pairs:
if not stack or stack.pop() != pairs[character]:
return False
return not stack
print(balanced("([])")) # TrueStacks also power undo histories, function calls, depth-first search, and expression evaluation.
Ask whether the newest open task must close first. If yes, a stack is probably nearby.
Your tiny challenge
Process the symbols ({[]}) by hand. Write the stack after every push and pop.
