
The Stack of Scrolls
A data structure is a way of organizing data so that certain operations are fast and easy. The first one is the stack.
Last in, first out
Picture the Guild archivist piling scrolls on a desk. New scrolls go on top, and the archivist always takes from the top. That's LIFO: last in, first out.
A Python list makes a perfect stack. Adding and removing at the end is fast (O(1)):
stack = []
stack.append("map") # push
stack.append("recipe") # push
print(stack[-1]) # peek -> recipe
print(stack.pop()) # pop -> recipe
print(stack) # ['map']
Where stacks shine
Stacks are great whenever the most recent thing must be handled first: undo history, the call stack, and matching brackets. When you see an opening bracket, push it. When you see a closing bracket, the top of the stack must be its partner.
Pip tip: Check for an empty stack before you
pop(), popping an empty list raisesIndexError.
Assignment
Complete is_balanced(text):
- Loop over every character. Ignore anything that isn't a bracket.
- Push opening brackets
(,[,{ontostack. - For a closing bracket, return
Falseif the stack is empty or its top isn't the matching opener (usePAIRS); otherwise pop. - At the end, the text is balanced only if the stack is empty.
Complete is_balanced(text):
- Loop over every character. Ignore anything that isn't a bracket.
- Push opening brackets
(,[,{ontostack. - For a closing bracket, return
Falseif the stack is empty or its top isn't the matching opener (usePAIRS); otherwise pop. - At the end, the text is balanced only if the stack is empty.
Press Run to try your code, then Check to test it.