A level · 6 exercises
Python 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.
Exercises
- Balanced bracketsCheck that every bracket (), [] and {} is closed by the right kind in the rightAdvanced
- Postfix calculatorEvaluate an expression in postfix notation (operators after their numbers), e.g.Advanced
- UndoA tiny editor: type <word> adds the word to the end of the text, undo cancels theAdvanced
- Counting outn people stand in a circle, numbered 1 to n.Advanced
- Next greater numberFor every number, print the first number to its right that is greater, or -1 ifAdvanced
- Back and forwardSimulate a browser starting at home: visit <page> opens a page (and clears theAdvanced