Start free

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

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