Skip to content
CodeItRaw
Stacks & Queues

Lesson 1/4

A stack is like a pile of plates: you only put on the top and only take from the top. Python needs no special type; a list does it: append puts on top, pop takes the top, stack[-1] looks at it.

PAIR = {")": "(", "]": "["}
stack = []
for ch in text:
if ch in "([":
stack.append(ch)
elif not stack or stack.pop() != PAIR[ch]:
return False
return not stack
Checking brackets is the textbook use of a stack: an opener is put on hold; when a closer arrives it must match the most recently opened one. A stack that is not empty at the end means something was never closed.

You know you need a stack when you are setting things aside to deal with later, and the last one set aside is the first you must deal with. Nested things (brackets, folders, function calls) are always like that.

Tasks

Tasks open in order. Solve them all and the next lesson opens.

This lesson's tasks open when the lessons before it are finished. You can read the explanation now.

  1. 01

    Bracket Tower

    Function

  2. 02

    Balanced Brackets

    Function

If you would rather not wait for the order, every problem is open without locks: Problem list