unfried.
Streak:0 days XP:0

Formula sheet

Data structures

99 entries in 12 units. Free to use and share.

Jump to a unit (12 units)

Unit 1 Classes and objects

Defining a class and making objects

Also called class, object, __init__, attribute, constructor.

Each call of the class makes a new object and runs __init__ on it, with self the new object. self.x = x stores an attribute on that object alone.

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(3, 4)
print(p.x + p.y)   # 7

Careful: A bare x = x in __init__ stores nothing on the object, and the call must not pass self: Point(3, 4) gives two arguments for x and y.

Taught in A class makes objects

Methods and self

Also called method, self, calling a method.

The object before the dot is passed as the first parameter, self. Read and change attributes as self.n.

class Counter:
    def __init__(self):
        self.n = 0
    def add(self):
        self.n += 1

c = Counter()
c.add()     # same as Counter.add(c)

Careful: A bare n inside a method is a local name, so n += 1 raises an error. Never write c.add(c).

Taught in Methods and self

__str__ for printing

Also called special method, printing an object, str.

print and str call __str__ and use the string it returns.

class Mass:
    def __init__(self, kg):
        self.kg = kg
    def __str__(self):
        return f"{self.kg} kg"

print(Mass(2.5))   # 2.5 kg

Careful: A __str__ that prints instead of returning hands back None. Inside a list, items show with __repr__, not __str__.

Taught in Printing an object

== and is for objects

Also called __eq__, identity, equality.

Write def __eq__(self, other): return self.kg == other.kg to make objects with equal attributes compare equal.

ExpressionAsksWithout __eq__
a is bone object?same
a == bequal, as __eq__ saysone object?
x in a_listany element == x?one object?

Careful: Two calls of a class are never is each other, whatever __eq__ says.

Taught in Equal or the same object

References, aliasing and copies

Also called reference, alias, passing objects to functions.

Names, parameters and list slots hold references. Only calling the class makes a new object.

CodeWhat happens
b = ab refers to a's object
f(a) with box.n = 10 insidechanges a's object
f(a) with box = Box(99) insidemoves the local name only
Box(a.n)a new object

Careful: Assigning to a parameter never changes the caller's variable; changing an attribute through it does change the caller's object.

Taught in Names refer to objects

A list of objects inside an object

Also called composition, mutable default argument, has a.

Build the list in __init__, so each object gets its own.

class Carton:
    def __init__(self):
        self.eggs = []
    def add(self, egg):
        self.eggs.append(egg)
    def weight(self):
        total = 0
        for e in self.eggs:
            total += e.grams
        return total

Careful: def __init__(self, eggs=[]) and eggs = [] in the class body each make one list that every object shares.

Taught in Objects inside objects

Abstract data type and interface

Also called ADT, interface, encapsulation.

An abstract data type is a set of operations and what each promises (a bag: add(x), count(x)). A class builds it on some storage, a list or a dictionary, which outside code never touches.

Careful: Code that reads an attribute such as b.items directly breaks when the storage changes; code that calls only the methods does not.

Taught in What it does, not how it stores it

Inheritance and super()

Also called subclass, overriding, super, is a.

A subclass inherits every method of its parent and writes only what differs. A method with the parent's name overrides it, and self.method() finds the subclass's version first.

class Thermo(Sensor):
    def __init__(self, name, unit):
        super().__init__(name)
        self.unit = unit

Careful: A subclass's own __init__ replaces the parent's: without super().__init__(…) the parent's attributes are never set.

Taught in A class built on another

Fraction class with __add__

Also called operator methods, __add__, lowest terms.

Python runs a.__add__(b) for a + b. Return a new object; making it through the class runs __init__, which can reduce it to lowest terms.

def __add__(self, other):
    top = self.num * other.den
    top += other.num * self.den
    bottom = self.den * other.den
    return Fraction(top, bottom)

Careful: An __add__ that prints, or that changes self, breaks print(a + b) or changes a.

Taught in Lab: A Fraction class

Unit 2 How fast is it?

Counting a loop's steps

Also called nested loop count, triangular loop, halving loop.

A loop inside a loop multiplies the counts; loops one after another add them.

LoopBody runs
for i in range(n)n
for j in range(n) inside for i in range(n)n2
for j in range(i) inside for i in range(n)n(n−1)/2
n = n // 2 while n > 1about log⁡2n

Careful: Count steps, not seconds: seconds change from machine to machine, the step count does not.

Taught in Count the steps

Big-O drops constants and smaller terms

Also called order of growth, simplifying a step count.

Keep the fastest-growing term without its constant: 3n2+100n+7 is O(n2)⁠, 2n is O(n)⁠, n(n−1)/2 is O(n2) and 500 is O(1)⁠.

Careful: Big-O describes large n. For small n the constants can decide: n2 steps are fewer than 100n until n = 100.

Taught in Big-O keeps the fastest-growing term

The common growth classes

Also called complexity classes, doubling n.

Slowest-growing first. log⁡2n is the number of halvings from n to 1: about 20 for a million.

ClassNameDoubling n
O(1)constantno change
O(log⁡n)logarithmicadds one step
O(n)lineardoubles
O(nlog⁡n)n log na bit more than doubles
O(n2)quadraticmultiplies by 4
O(2n)exponentialsquares

Taught in The common growth classes

Reading big-O off loops

Also called sequential loops add, nested loops multiply.

Loops one after another add (n + n is O(n)⁠). A loop inside a loop multiplies (n × n is O(n2)⁠, and so is j<i⁠). A loop that halves or doubles is O(log⁡n)⁠. A loop with a fixed count is O(1)⁠.

Careful: A nested loop with a constant inner count (range(10)) is only O(n)⁠. And one line can hide a loop: x in a_list inside an n-pass loop is O(n2)⁠.

Taught in Read big-O off the code

Best, worst and average case of linear search

Also called worst case, best case.

Best case 1 comparison (target first); worst case n (target last or missing); average (n+1)/2 when the target is present and equally likely anywhere. All but the best case are O(n)⁠.

Careful: A big-O with no case named means the worst case.

Taught in Best case and worst case

Python list costs

Also called list time complexity, pop(0), insert.

OperationCost
xs[i], xs.append(x), xs.pop()O(1) (append amortized)
xs.pop(0), xs.insert(0, x)O(n)
x in xs, xs.remove(x)O(n)
xs[a:b], a slice of k itemsO(k)
sorted(xs)O(nlog⁡n)

Careful: Working at the front of a list shifts every other item. A line that calls one of the O(n) operations inside an n-pass loop makes it O(n2)⁠.

Taught in What Python's operations cost

Set and dictionary costs

Also called constant time, hash lookup.

A set or a dictionary goes straight to where a value or key would be stored, so a check takes about the same time for 10 items or 10 million.

OperationCost
x in s, s.add(x)O(1) on average
k in d, d[k], d[k] = vO(1) on average

Careful: Sets and dictionaries keep no order you can rely on. Print them through sorted.

Taught in What Python's operations cost

Four anagram checks

MethodCost
cross off each letter from a copyO(n2)
sort both and compareO(nlog⁡n)
try every rearrangementO(n!)
count the letters into two lists of 26O(n)

Careful: For very short words big-O can't pick the winner: the constant costs decide.

Taught in One problem, four algorithms

Unit 3 Stacks

Stack operations and their costs

Also called push, pop, peek, is_empty, size, LIFO, list-based stack.

n is the number of items. Last in, first out: a pop returns the item pushed most recently.

OperationList codeCost
pushself.items.append(x)O(1)
popself.items.pop()O(1)
peekself.items[-1]O(1)
is_empty, sizenot self.items, len(self.items)O(1)
push, top at index 0self.items.insert(0, x)O(n)

Careful: Keep the top at the end of the list. With the top at index 0, every push and pop shifts all the other items.

Taught in A Stack class

Popping an empty stack

Also called IndexError, empty stack, guard.

Callers check first with while not s.is_empty():, or catch the error with except IndexError.

def pop(self):
    if not self.items:
        raise IndexError("empty")
    return self.items.pop()

Careful: Returning None for an empty stack can't be told apart from a stored None.

Taught in Popping an empty stack

Balanced brackets with a stack

Also called bracket matching, parentheses checker.

PAIRS = {")": "(", "]": "["} maps each closer to its opener. O(n) for a string of length n.

def balanced(s):
    stack = []
    for ch in s:
        if ch in "([":
            stack.append(ch)
        elif ch in PAIRS:
            if not stack:
                return False
            top = stack.pop()
            if top != PAIRS[ch]:
                return False
    return not stack

Careful: Equal counts of opening and closing brackets don't make a string balanced: "([)]" closes in the wrong order.

Taught in Balanced brackets

Converting to binary or another base

Also called decimal to binary, base conversion, to_base.

The remainders arrive last digit first, and the pops reverse them: 13 gives 1101. For base b, use n % b and n // b, with digits from "0123456789ABCDEF".

def to_binary(n):
    stack = []
    while n > 0:
        stack.append(n % 2)
        n = n // 2
    out = ""
    while stack:
        out += str(stack.pop())
    return out

Careful: This version returns an empty string for 0, because the loop never runs. Test for 0 first if you need "0".

Taught in Stacks reverse things

Evaluating postfix

Also called reverse Polish notation, RPN, eval_postfix.

Push each number. At an operator, pop b, then pop a, and push a op b. A well-formed expression leaves exactly one number: 3 4 + 2 * is 14.

Careful: The first number popped is the right operand: 7 2 - is 5, not -5.

Taught in Postfix expressions

Infix to postfix (shunting-yard)

Also called operator precedence, infix, Dijkstra.

Operands go straight out. Before pushing an operator, pop every operator on top with equal or higher precedence (* / above + -). Push (; at ), pop back to the (. At the end, pop the rest. A + B * C becomes A B C * +.

Careful: The operators don't keep their written order: one of higher precedence comes out first unless brackets say otherwise.

Taught in Infix to postfix by hand

Unit 4 Queues and deques

Queue (first in, first out)

Also called FIFO, enqueue, dequeue, front and rear.

Enqueue adds at the rear; dequeue removes the item at the front, the one that has waited longest. Items leave in the order they arrived, however the operations are mixed. Drawn front → [a, b, c] ← rear.

Careful: A stack is last in, first out. Removing from the same end you add to is a stack, not a queue.

Taught in First in, first out

Queue on a Python list

Also called Queue class, pop(0), dequeue cost.

The front is index 0 and the rear is the end of the list. Enqueue, is_empty, size and peeking at items[0] are O(1)⁠; dequeue is O(n) for n items.

class Queue:
    def __init__(self):
        self.items = []
    def enqueue(self, item):
        self.items.append(item)
    def dequeue(self):
        return self.items.pop(0)
    def is_empty(self):
        return self.items == []
    def size(self):
        return len(self.items)

Careful: pop(0) shifts every other item, so dequeuing all n items is O(n2) in total. On a computer, collections.deque with popleft is O(1)⁠.

Taught in A Queue class

Hot potato (rotate a queue)

Also called circle simulation, Josephus, round robin.

A pass moves the front item to the rear. After num passes, a dequeue with no enqueue removes the holder. With n players, n − 1 rounds leave one.

for i in range(num):
    q.enqueue(q.dequeue())
q.dequeue()

Careful: Holding the potato at the start is not a pass; with num = 0 players leave in queue order.

Taught in Hot potato

Queue from two stacks

Also called two-stack queue, inbox and outbox, Queue2, amortized O(1).

Enqueue pushes onto the inbox. Moving the inbox onto an empty outbox reverses it, so the oldest item is on top. Each item moves at most once, so dequeue is O(1) amortized, O(n) in the worst single call.

def dequeue(self):
    if not self.outbox:
        while self.inbox:
            x = self.inbox.pop()
            self.outbox.append(x)
    return self.outbox.pop()

Careful: Refill only when the outbox is empty; refilling a non-empty outbox lets newer items leave before older ones.

Taught in A queue from two stacks

Deque operations and costs

Also called double-ended queue, add_front, remove_rear, deck.

One end only makes a deque a stack; rear in and front out makes it a queue. The front is index 0.

MethodList callCost on a list
add_frontinsert(0, item)O(n)
add_rearappend(item)O(1)
remove_frontpop(0)O(n)
remove_rearpop()O(1)

Careful: collections.deque makes all four O(1)⁠; a list makes the front ones O(n)⁠.

Taught in Deques

Palindrome check with a deque

Also called is_palindrome, compare both ends.

Remove and compare the two end letters while at least two are left. One letter or none left means every pair matched.

def is_palindrome(word):
    d = list(word)
    while len(d) > 1:
        if d.pop(0) != d.pop():
            return False
    return True

Careful: With a list, each pop(0) is O(n)⁠, so the check is O(n2)⁠; with collections.deque and popleft it is O(n)⁠.

Taught in Deques

Choosing a stack, a queue or a deque

Also called which structure, LIFO or FIFO.

Ask which item the task must take out next; all three can store the same items.

Next item outStructureExamples
The newestStackundo, back button, brackets
The oldestQueueprinter, help line
Either endDequepalindrome, capped undo history

Taught in Which structure fits?

Unit 5 Linked lists

Node class

Also called node, linked list.

A node holds a value in data and a reference to the next node in next. a.next = b links the node a refers to to the node b refers to.

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

Careful: a.next = b stores a reference, not a copy: a change through b shows through a.next. Moving the name b later leaves the link alone.

Taught in Nodes and links

Walking a linked list

Also called traverse, traversal, length, total.

A separate name cur visits every node from the head to the end. The test is true on the last node, and an empty list skips the loop.

cur = head
while cur is not None:
    print(cur.data)
    cur = cur.next

Careful: while cur.next is not None: skips the last node and crashes on an empty list. Walking by moving head itself loses the list.

Taught in Walking a list

Adding at the front

Also called push_front, insert at head.

Link the new node to the old first node, then move the head. O(1)⁠, and it works on an empty list.

def push_front(self, data):
    n = Node(data)
    n.next = self.head
    self.head = n

Careful: With self.head = n first, the new node points at itself and the rest of the list is lost.

Taught in Adding at the front

Getting position k

Also called get, index into a linked list.

Positions count from 0, so reaching position k takes k moves: O(n) for n nodes, where xs[k] on a Python list is O(1)⁠.

def get(head, k):
    cur = head
    for _ in range(k):
        cur = cur.next
    return cur.data

Careful: A k past the last position runs off the end and fails on None.data. Calling get for every k is O(n2)⁠; walk once instead.

Taught in Finding the k-th item

Removing a node by value

Also called remove, delete from a linked list.

prev.next = cur.next links the node before past the target. The head has no node before it, so its removal returns head.next. The caller stores the result: h = remove(h, 8).

def remove(head, target):
    prev = None
    cur = head
    while cur is not None:
        if cur.data == target:
            if prev is None:
                return cur.next
            prev.next = cur.next
            return head
        prev = cur
        cur = cur.next
    return head

Careful: cur = None removes nothing, since no link changes. prev.next = None cuts off every node after the target too.

Taught in Removing a node

Appending, without and with a tail

Also called append, add at the end, tail reference.

The walk stops on the last node, the one whose next is None. A tail reference reaches it at once; an empty list sets head and tail both to the new node.

while cur.next is not None:
    cur = cur.next
cur.next = n          # walk: O(n)

self.tail.next = n
self.tail = n         # with a tail: O(1)

Careful: Every method that changes the last node, such as removing it, must also update tail.

Taught in Adding at the end

Reversing a linked list in place

Also called reverse.

Each pass saves the rest, turns one link back and moves both names on. O(n) work, three extra names, no new nodes. prev ends on the new head.

prev = None
cur = head
while cur is not None:
    nxt = cur.next
    cur.next = prev
    prev = cur
    cur = nxt
return prev

Careful: Changing cur.next before saving it loses the rest of the list, and cur = cur.next after the turn moves backward.

Taught in Reversing a list

Linked list against Python list

Also called cost table, big-O of linked list operations.

n is the number of items. Each structure is O(1) for different operations, so the task decides.

OperationLinked list (head, tail)Python list
Add at the frontO(1)O(n)
Remove the firstO(1)O(n)
Add at the endO(1)O(1)
Remove the lastO(n)O(1)
Read position kO(n)O(1)
Search for a valueO(n)O(n)

Careful: The linked-list column assumes a singly linked list that keeps a tail; without one, adding at the end is O(n)⁠.

Taught in Linked list or Python list?

Doubly linked list

Also called prev reference.

Each node also keeps prev, the node before it, and the list keeps head and tail. Removing a node you hold is O(1)⁠: node.prev.next = node.next and node.next.prev = node.prev. Removing the last node is O(1) too.

Careful: Reaching position k still means walking, so indexing stays O(n)⁠.

Taught in Linked list or Python list?

Inserting into a sorted linked list

Also called insert_sorted, ordered list.

First handle an empty list and an x no bigger than the head's value: the new node is the new head. Otherwise walk to the node in front of the gap and link the new node in, rest first. O(n) per insert.

cur = head
while cur.next is not None:
    if cur.next.data >= x:
        break
    cur = cur.next
n.next = cur.next
cur.next = n

Careful: Linking cur.next = n first makes the new node point at itself.

Taught in Lab: Keep it sorted

Unit 6 Recursion

Base case and recursive case

Also called recursion, recursive function.

The base case returns without calling. The recursive case calls the function on a smaller value and returns what it builds from the result.

def fact(n):
    if n == 0:
        return 1
    return n * fact(n - 1)

Careful: With no base case, or calls that never reach it, Python stops with RecursionError (this app: RuntimeError) after about 1000 calls (this app: about 150).

Taught in A function that calls itself

The call stack

Also called stack frame, order of recursive calls.

Each call has its own frame with its own variables. The newest call is on top and finishes first. A line after the recursive call runs as the calls return, innermost first: up(3) prints 1, 2, 3.

def up(n):
    if n > 0:
        up(n - 1)
        print(n)

Careful: The calls don't share one n, and the lines after the call aren't skipped: they wait.

Taught in Each call waits its turn

Returning from every branch

Also called recursive return value, None from recursion.

The recursive case builds its answer from the call's result and returns it.

def total(xs):
    if len(xs) == 0:
        return 0
    return xs[0] + total(xs[1:])

Careful: A recursive case without return hands back None, and the waiting call fails on + None.

Taught in Returning a value

The three laws of recursion

A base case, a move toward it with every call, and a call to itself on the smaller problem.

FunctionBase caseSmaller step
reverse(s)s == ""s[1:]
digits(n)n < 10n // 10
is_pal(s)len(s) < 2s[1:-1]
power(b, n)n == 0n - 1

Careful: A call on the same problem (s[0:], n) or one that steps past the base case (n − 2 from an odd n to n == 0) never stops.

Taught in The three laws

Calls of recursive Fibonacci

Also called recursion tree, exponential recursion.

Plain fib makes two calls per call and repeats subproblems: about 1.6 times more calls per step, O(2n)⁠. With a memo it makes 2n − 1 calls, O(n)⁠.

ncalls of plain fib(n)with a memo
5159
1017719
2021,89139
30about 2.7 million59

Taught in Two calls at once

Memoization

Also called memo, caching results.

Look the answer up first; otherwise compute it, store it and return it. Every answer is unchanged; only repeated work is saved.

memo = {}

def fib(n):
    if n < 2:
        return n
    if n in memo:
        return memo[n]
    value = fib(n - 1) + fib(n - 2)
    memo[n] = value
    return value

Careful: A memo made inside the function is empty in every call and saves nothing. A function that never repeats a subproblem, like fact, gains nothing.

Taught in Remember the answers

Fewest coins (dynamic programming)

Also called making change, coin change, greedy algorithm.

Fill best from 0 up: best[0] is 0, and each amount tries every coin as the last one. The work is the amount times the number of coins, O(n) for a fixed set.

for a in range(1, amount + 1):
    best[a] = a
    for c in coins:
        if c > a:
            continue
        t = best[a - c] + 1
        if t < best[a]:
            best[a] = t

Careful: Largest coin first (greedy) can fail: coins 1, 3, 4 for 6 gives 3 coins instead of 2. Starting at best[a] = a assumes a 1-cent coin; without one, start at amount + 1 and report −1 when it is never improved.

Taught in Making change

Tower of Hanoi

Also called hanoi moves.

moves(n) = 2 × moves(n − 1) + 1, so n disks take 2n−1 moves: 1, 3, 7, 15 … 1023 for 10 disks. O(2n)⁠.

def hanoi(n, src, dst, spare):
    if n == 0:
        return
    hanoi(n - 1, src, spare, dst)
    print(src, "->", dst)
    hanoi(n - 1, spare, dst, src)

Careful: The moves don't grow like n²: 64 disks at one move per second would take about 585 billion years.

Taught in The Tower of Hanoi

Unit 7 Searching and hashing

Binary search

Also called bsearch, halving search, lo and hi bounds.

The list must be sorted. lo and hi are both included, so the loop runs while lo <= hi, and each miss moves a bound past mid. Returns the index of t, or -1.

def bsearch(xs, t):
    lo = 0
    hi = len(xs) - 1
    while lo <= hi:
        mid = (lo + hi) // 2
        if xs[mid] == t:
            return mid
        elif xs[mid] < t:
            lo = mid + 1
        else:
            hi = mid - 1
    return -1

Careful: while lo < hi misses the last item in play, hi = mid can loop forever, and lo + hi // 2 is not the middle. On an unsorted list the answer can be wrong.

Taught in Writing binary search

Worst-case comparisons of binary search

Also called log2 n, number of halvings.

n
number of items in the sorted list

Applies: The count of items compared in the worst case, one per halving plus the last item. It is 7 for 100 items, 10 for 1000 and 20 for a million.

Careful: Linear search needs up to n comparisons. Doubling n adds one comparison here, but doubles linear search's work.

Taught in Halving a sorted list

Recursive binary search costs

Also called slicing, contains, find with bounds.

A slice of k items costs O(k)⁠, and the copies add up to about n. Passing bounds copies nothing; start with find(xs, t, 0, len(xs) - 1).

VersionCallsTotal work
Slices xs[:mid], xs[mid + 1:]about log⁡2nO(n)⁠, from copying
Bounds find(xs, t, lo, hi)about log⁡2nO(log⁡n)

Taught in Binary search by recursion

Remainder hash function

Also called hash table, slot, key mod m.

s
the home slot of the key
k
the integer key
m
number of slots in the table

Applies: Each key goes to its home slot, the remainder, from 0 to m − 1. A lookup computes the same slot, O(1) when no keys collide.

Careful: The quotient k // m is not the slot. Keys sit in slot order, not in the order they arrived or in sorted order.

Taught in Hash functions

Linear probing

Also called open addressing, collision, put and has.

A taken home slot sends the key to the next free slot, wrapping round after the last. A lookup probes the same path and stops at the key or at an empty slot.

def put(table, key):
    i = key % len(table)
    while table[i] is not None:
        i = (i + 1) % len(table)
    table[i] = key

Careful: A different key in the home slot does not mean the key is missing; only an empty slot does.

Taught in Collisions: linear probing

Chaining

Also called separate chaining, a list per slot.

Each slot holds a list of the keys with that home slot. A lookup searches only that list: key in slot.

table = [[] for _ in range(11)]
def put(table, key):
    slot = table[key % len(table)]
    slot.append(key)

Careful: [[]] * 11 makes 11 references to one list, so every slot shares a single chain.

Taught in Collisions: chaining

Load factor

Also called lambda, fullness, average chain length.

λ
load factor
n
number of keys stored
m
number of slots

Applies: With chaining an average chain holds λ keys, so a lookup is O(1+λ)⁠. 9 keys in 11 slots give λ ≈ 0.82.

Careful: A table that never grows gets slower as n rises, since λ rises with it.

Taught in Collisions: chaining

Expected probes with linear probing

Also called full table, probe counts.

Standard estimates of the average number of slots a lookup checks. A missing key costs about 12(1+1/(1−λ)2) slots.

λKey foundKey missing
0.251.21.4
0.501.52.5
0.752.58.5
0.905.550.5

Careful: The cost climbs steeply near full, so tables grow (rehash) well before λ reaches 1.

Taught in Full tables and Python's dictionaries

Rehashing

Also called resizing, growing a hash table, amortized insert.

Once λ passes a threshold, make a table about twice as big and put every key in again by its new slot, since key % m changes with m. Rehashing is O(n) but rare, so inserts are O(1) amortized.

Careful: Copying keys slot for slot leaves them where lookups in the bigger table will not look.

Taught in Full tables and Python's dictionaries

Hashable keys

Also called unhashable, dictionary keys, set members, immutable.

Python's dict and set are hash tables, so keys and members must be immutable. d[[1, 2]] = "x" raises TypeError: unhashable type: 'list'.

Can be a keyCannot be a key
42, 3.5, "apple"[3, 4]
(3, 4){"a": 1}, {1, 2}

Careful: A tuple that holds a list, such as (1, [2]), is unhashable too.

Taught in Full tables and Python's dictionaries

String hash functions

Also called hashing strings, ord, positional hash, anagrams.

Adding the ord codes sends anagrams ("cat", "act", "tac") to one slot. Multiplying by 31 before each add weights characters by position, so rearranged letters usually land apart. Hashing a key of k characters is O(k)⁠.

def pos_hash(word):
    h = 0
    for ch in word:
        h = h * 31 + ord(ch)
    return h % 11

Careful: No hash into a few slots prevents every collision: "tac" and "dog" share slot 6. Probing or chaining handles the rest.

Taught in Hashing strings

Unit 8 Sorting

Bubble sort

Also called pass, swap, early exit, bubble_sort.

Each pass carries the largest unplaced item to the end. n(n − 1)/2 comparisons, O(n2)⁠. With a swapped flag that stops after a pass with no swap, a sorted list takes one pass, O(n)⁠.

def bubble_sort(xs):
    n = len(xs)
    for p in range(n - 1):
        for i in range(n - 1 - p):
            if xs[i] > xs[i + 1]:
                swap(xs, i, i + 1)

Careful: One pass does not sort the list; it only puts the largest item in its final place.

Taught in Bubble sort

Selection sort

Also called selection_sort, smallest remaining item.

Each pass finds the smallest unsorted item and swaps it into index p. Always n(n − 1)/2 comparisons, but at most n − 1 swaps.

def selection_sort(xs):
    n = len(xs)
    for p in range(n - 1):
        m = p
        for i in range(p + 1, n):
            if xs[i] < xs[m]:
                m = i
        swap(xs, p, m)

Careful: It is O(n2) even on a sorted list, and it is not stable.

Taught in Selection sort

Insertion sort

Also called insertion_sort, shift right, nearly sorted.

Each pass shifts the larger items of the sorted front one place right and puts x in the gap. n − 1 comparisons on sorted input, about n²/2 on reversed input.

def insertion_sort(xs):
    for i in range(1, len(xs)):
        x = xs[i]
        j = i - 1
        while j >= 0 and xs[j] > x:
            xs[j + 1] = xs[j]
            j -= 1
        xs[j + 1] = x

Careful: Save x before shifting; the first shift writes over xs[i].

Taught in Insertion sort

Simple sorts compared (8 items)

Also called comparisons and swaps, bubble selection insertion.

Comparisons first, then swaps or shifts, for 8 items. Insertion sort is the one that gains from nearly sorted input.

SortSortedReversedOne pair swapped
Bubble (no early stop)28, 0 swaps28, 28 swaps28, 1 swap
Selection28, 0 swaps28, 4 swaps28, 1 swap
Insertion7, 0 shifts28, 28 shifts8, 1 shift

Taught in Comparing the simple sorts

Stable sort

Also called stability, equal keys, ties.

A stable sort keeps items with equal keys in their original order, so sorting by one key and then stably by another keeps the first order within ties. Stable: bubble, insertion, merge sort with <=, Timsort. Not stable: selection sort, quicksort with an in-place partition.

Careful: Stable does not mean the sort never fails, and moving an item past an equal one (>= in insertion sort) breaks it.

Taught in Comparing the simple sorts

Merge two sorted lists

Also called merge, two-finger merge.

At most n − 1 comparisons for n items in all, O(n)⁠. <= takes from a on a tie, which keeps the merge stable.

def merge(a, b):
    out = []
    i = j = 0
    na, nb = len(a), len(b)
    while i < na and j < nb:
        if a[i] <= b[j]:
            out.append(a[i])
            i += 1
        else:
            out.append(b[j])
            j += 1
    return out + a[i:] + b[j:]

Careful: Without the leftovers a[i:] + b[j:], the tail of the longer list is lost.

Taught in Merging two sorted lists

Merge sort

Also called merge_sort, divide and conquer, n log n.

About log⁡2n levels of halving, each merging all n items: O(nlog⁡n) in every case, O(n) extra memory, 2n − 1 calls.

def merge_sort(xs):
    if len(xs) <= 1:
        return xs
    mid = len(xs) // 2
    left = merge_sort(xs[:mid])
    right = merge_sort(xs[mid:])
    return merge(left, right)

Careful: Halving does not make it O(log⁡n)⁠; every level still merges all n items.

Taught in Merge sort

Quicksort

Also called pivot, partition, quicksort worst case.

partition puts the items smaller than the first item in lo and the rest in hi. Even splits: O(nlog⁡n)⁠. First item as pivot on sorted or reversed input: n levels, n(n − 1)/2 comparisons, O(n2)⁠.

def quicksort(xs):
    if len(xs) <= 1:
        return xs
    lo, pivot, hi = partition(xs)
    a = quicksort(lo)
    b = quicksort(hi)
    return a + [pivot] + b

Careful: It is not always O(nlog⁡n)⁠; use a random or middle pivot when the input may already be sorted.

Taught in Quicksort

Choosing a sort

Also called sort costs, Timsort, sorted, comparison lower bound.

A comparison sort needs about nlog⁡2n comparisons in the worst case. Merge sort uses O(n) extra memory; in-place quicksort uses almost none.

SortWorstBestStable
InsertionO(n2)O(n) sortedYes
SelectionO(n2)O(n2)No
MergeO(nlog⁡n)O(nlog⁡n)Yes
Quick, in placeO(n2)O(nlog⁡n)No
Timsort (sorted)O(nlog⁡n)O(n) sortedYes

Careful: No comparison sort beats nlog⁡2n in the worst case; counting sorts can, for small whole-number keys only.

Taught in Choosing a sort

Unit 9 Trees and traversals

Tree words

Also called root, leaf, parent, child, subtree, depth.

The root has no parent; a leaf has no children. A node's children are the nodes directly below it, and the subtree at a node is that node with everything below it. Depth is the number of edges from the root (the root has depth 0). A tree with n nodes has n − 1 edges.

Careful: A leaf need not be on the bottom level: any node with no children is one.

Taught in Tree words

Height of a tree

Also called tree height, counting edges.

The number of edges on the longest path from the root down to a leaf. One node has height 0 and the empty tree −1.

Careful: Some books count the nodes on the path, which gives one more. This course counts edges.

Taught in Tree words

Binary tree node

Also called Node class, left and right.

A binary tree is None (empty) or a Node whose left and right are binary trees. make([8, [3], [10, None, [14]]]) builds nodes from [value, left, right], with None for an empty side.

class Node:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

Careful: Left and right differ: 2 with a left child 5 is not the same tree as 2 with a right child 5.

Taught in A binary tree in code

Recursion on a binary tree

Also called size, height, sum, leaves, empty tree base case.

Answer the empty tree with no call, then combine the two subtrees' answers. Each visits every node once: O(n) for n nodes.

def size(t):
    if t is None:
        return 0
    left = size(t.left)
    right = size(t.right)
    return 1 + left + right
FunctionEmpty treeAny other node
size01 + left + right
height−11 + max(left, right)
sum of values0t.val + left + right
leaves01 if no children, else left + right

Careful: A base case that tests only for a leaf crashes on a node with one child: the call on its empty side reads None.left.

Taught in Recursion on trees

Preorder, inorder and postorder

Also called depth-first traversal, tree traversal.

Only the place of the print changes: before both calls, between them or after them. Each is O(n)⁠.

def inorder(t):
    if t is None:
        return
    inorder(t.left)
    print(t.val)
    inorder(t.right)
OrderVisitsTree with root 8 in this unit
Preordernode, left, right8 3 1 6 4 7 10 14 13
Inorderleft, node, right1 3 4 6 7 8 10 13 14
Postorderleft, right, node1 4 7 6 3 13 14 10 8

Careful: Inorder comes out sorted only when smaller values sit on the left, as in a binary search tree.

Taught in Three depth-first orders

Level-order traversal

Also called breadth-first traversal, level order with a queue.

Visits the nodes by depth, left to right, using a queue. The tree with root 8 gives 8 3 10 1 6 14 4 7 13. O(n) with collections.deque and popleft.

q = []
if t is not None:
    q.append(t)
while q:
    node = q.pop(0)
    print(node.val)
    if node.left is not None:
        q.append(node.left)
    if node.right is not None:
        q.append(node.right)

Careful: With a stack (pop()) the order goes deep first, and a recursive function can't give level order directly.

Taught in Level by level

Expression tree

Also called evaluate, postfix from a tree.

Leaves are numbers and every other node is an operator with two children. The value is worked out in postorder, and the postorder is the postfix form: (3 + 4) * 2 gives 3 4 + 2 * and 14.

def evaluate(t):
    if t.left is None:
        return t.val
    a = evaluate(t.left)
    b = evaluate(t.right)
    return apply(t.val, a, b)

Careful: Inorder gives the infix form without brackets, so (3 + 4) * 2 prints as 3 + 4 * 2.

Taught in Expression trees

Unit 10 Binary search trees

Binary search tree rule

Also called BST property, BST invariant.

At every node, every value in the left subtree is smaller than the node's value and every value in the right subtree is larger. Equivalently, the inorder traversal is increasing.

Careful: Checking each node against its two children is not enough: a value can be in order with its parent and on the wrong side of an ancestor.

Taught in The search-tree rule

Searching a BST

Also called contains, BST lookup.

One comparison per level, so at most h + 1 nodes for height h: O(h)⁠.

def contains(t, x):
    while t is not None:
        if x == t.val:
            return True
        if x < t.val:
            t = t.left
        else:
            t = t.right
    return False

Careful: Reaching None means the value is missing; a search never needs to try the other side.

Taught in Searching a BST

Inserting into a BST

Also called BST insert, recursive insert.

The new value becomes a leaf where a search for it would fail. Call it as root = insert(root, x). O(h)⁠.

def insert(t, x):
    if t is None:
        return Node(x)
    if x < t.val:
        t.left = insert(t.left, x)
    else:
        t.right = insert(t.right, x)
    return t

Careful: Writing t = Node(x), or calling insert(t.left, x) without storing the result, never links the new node to its parent.

Taught in Inserting

Cost of BST operations

Also called BST height, balanced tree, degenerate tree.

The first value inserted is the root, and insertion order sets the shape. AVL and red-black trees rebalance to keep h at O(log⁡2n)⁠.

ShapeHeight hSearch, insert, delete
Balancedabout log⁡2nO(log⁡2n)
Chain (sorted input)n − 1O(n)
AnyhO(h)

Careful: A plain BST is not always O(log⁡2n)⁠: values inserted in sorted order make a chain.

Taught in Shape depends on order

Smallest and largest value

Also called minimum, maximum, BST min.

Walk left to the end for the smallest, right to the end for the largest. O(h)⁠. The tree must not be empty.

def smallest(t):
    while t.left is not None:
        t = t.left
    return t.val

Careful: The node found need not be a leaf: the smallest can have a right child.

Taught in Smallest, largest, sorted

Tree sort

Also called sorting with a BST.

Insert every value into an empty BST, then read it inorder. O(nlog⁡2n) while the tree stays balanced.

Careful: On input that is already sorted the tree is a chain and the sort is O(n2)⁠.

Taught in Smallest, largest, sorted

Deleting from a BST

Also called BST delete, inorder successor.

The inorder successor is the smallest value in the right subtree; it has no left child. The predecessor, the largest on the left, works too. O(h)⁠.

Node to deleteWhat happens
LeafRemoved: its parent's link becomes None
One childThat child takes its place
Two childrenCopy in the inorder successor, then delete the successor from the right subtree

Careful: In general neither child can move up in its place, and deleting the node must not remove its subtrees.

Taught in Deleting a node

Checking the BST rule with ranges

Also called is_bst, validate a BST.

Start with within(t, -INF, INF), where INF = float("inf"). Each left subtree gets hi = t.val, each right subtree lo = t.val. O(n)⁠: every node once.

def within(t, lo, hi):
    if t is None:
        return True
    if not lo < t.val < hi:
        return False
    a = within(t.left, lo, t.val)
    b = within(t.right, t.val, hi)
    return a and b

Careful: Dropping the bound inherited from above lets a value on the wrong side of an ancestor through.

Taught in Lab: Is it a BST?

Unit 11 Heaps and priority queues

Priority queue storage costs

Also called priority queue, remove-min, insert, heap vs sorted list.

A priority queue removes the item with the smallest priority first, whatever order the items arrived in. n is the number of items stored.

StorageInsertRemove smallest
Unsorted listO(1)O(n)
Sorted list, smallest lastO(n)O(1)
HeapO(log⁡n)O(log⁡n)

Careful: A queue serves in arrival order; a priority queue ignores arrival order except to break ties when the program says how.

Taught in Smallest first

Min-heap property

Also called heap order, complete binary tree, heap shape.

A min-heap is a complete binary tree (every level full except possibly the last, which fills from the left) in which every parent is no larger than each of its children. The root holds the smallest value; the largest is at a leaf.

Careful: Siblings are not ordered and the list is usually not sorted. A binary search tree's left-and-right order is a different rule.

Taught in The heap property

Heap index formulas (0-based list)

Also called parent index, left child, right child, heap in a list.

The tree is stored level by level, left to right, with no gaps. A child index at or past len(h) means that child is missing.

NodeIndex
The root0
Parent of i(i - 1) // 2
Left child of i2 * i + 1
Right child of i2 * i + 2

Careful: Formulas i // 2, 2i and 2i + 1 are for a list that starts at index 1 with index 0 left empty; on a 0-based list they find the wrong nodes.

Taught in A heap in a list

Heap push (sift up)

Also called heap insert, sift up, bubble up, heappush.

Append at the end, then swap with the parent while the parent is larger. At most one swap per level: O(log⁡n) for n items.

def push(h, x):
    h.append(x)
    i = len(h) - 1
    while i > 0:
        p = (i - 1) // 2
        if h[p] <= h[i]:
            break
        swap(h, i, p)
        i = p

Careful: After a swap, carry on from the parent's index p, not from i - 1.

Taught in Insert: sift up

Heap pop (sift down)

Also called remove the minimum, sift down, pop_min, heappop.

To pop, keep h[0], move the last item (h.pop()) to the root if any items are left, and sift it down with the smaller child. O(log⁡n)⁠; popping all n items gives them sorted in O(nlog⁡n) (heap sort).

def sift_down(h, i):
    n = len(h)
    while 2 * i + 1 < n:
        c = 2 * i + 1
        r = c + 1
        if r < n and h[r] < h[c]:
            c = r
        if h[i] <= h[c]:
            break
        swap(h, i, c)
        i = c

Careful: Always compare with the smaller child, and check r < n before reading h[r]; a node can have a left child only.

Taught in Remove the minimum: sift down

Python's heapq module

Also called heappush, heappop, heapify, priority tuples.

Works on a plain list as a min-heap from index 0. Push (priority, item) tuples to order by priority; ties compare the next item. heapify returns None.

CallDoesCost
heappush(h, x)push and sift upO(log⁡n)
heappop(h)remove and return the smallestO(log⁡n)
heapify(h)make a list a heap in placeO(n)
h[0]read the smallestO(1)

Careful: To break ties by arrival rather than by name, push (priority, i, name) with an arrival number i.

Taught in Heaps in Python

The k largest items with a heap

Also called top k, k_largest, nlargest, streaming maximum.

A min-heap of at most k items holds the best k so far; its root is the next to drop. O(nlog⁡k) for n items.

def k_largest(xs, k):
    h = []
    for x in xs:
        heapq.heappush(h, x)
        if len(h) > k:
            heapq.heappop(h)
    return sorted(h)

Careful: Pop when the heap holds k + 1 items, not k, or only k − 1 are kept.

Taught in Heaps in Python

Unit 12 Graphs

Adjacency list

Also called graph as a dictionary, out-degree.

Each vertex maps to the list of vertices its arrows point to. len(g[v]) is the out-degree, and the edges are the sum of the list lengths: 7 here. An undirected edge appears in both lists.

g = {"A": ["B", "C"],
     "B": ["D"],
     "C": ["D", "E"],
     "D": ["F"], "E": ["F"],
     "F": []}
for v in sorted(g):
    print(v, len(g[v]))

Careful: Loop over sorted(g), not g, when the order reaches the output: this app's dictionaries don't keep insertion order.

Taught in Graphs in code

Adjacency list or adjacency matrix

Also called graph space, adjacency matrix.

m[i][j] is 1 for an arrow from vertex i to vertex j. With V vertices and E edges, lists are far smaller when each vertex has few neighbors.

RepresentationSpaceIs there u → v?
Adjacency listsO(V+E)O(d)⁠, d neighbors of u
Adjacency matrixO(V2)O(1)

Careful: A matrix stores a cell for every pair, joined or not: 1000 vertices take a million cells whatever the number of edges.

Taught in Graphs in code

Breadth-first search (BFS)

Also called BFS, visited set, queue search.

Visits vertices in order of distance from the start. Mark a vertex as seen when it joins the queue, so none is queued twice. O(V+E) with an O(1) dequeue such as collections.deque.

def bfs(g, start):
    seen = {start}
    q = [start]
    order = []
    while q:
        v = q.pop(0)
        order.append(v)
        for w in g[v]:
            if w not in seen:
                seen.add(w)
                q.append(w)
    return order

Careful: Without the seen check, or with q.append(w) outside the if, shared neighbors are visited twice and a cycle never ends.

Taught in Breadth-first search

Fewest edges and the route (BFS)

Also called shortest path, BFS distance, parent links.

The BFS distance dist[w] = dist[v] + 1 is the fewest edges from the start. Walk back through the parents from the goal and reverse to get a fewest-edge route.

def path(g, start, goal):
    parent = {start: None}
    q = [start]
    while q:
        v = q.pop(0)
        for w in g[v]:
            if w not in parent:
                parent[w] = v
                q.append(w)
    if goal not in parent:
        return None
    route = []
    v = goal
    while v is not None:
        route.append(v)
        v = parent[v]
    return route[::-1]

Careful: BFS counts edges and ignores weights; for least total weight use Dijkstra.

Taught in Fewest edges

Depth-first search (DFS)

Also called DFS, recursive graph search.

Goes as deep as it can along the first unseen neighbor, then backs up. Called as dfs(g, "A", []). O(V+E)⁠.

def dfs(g, v, seen):
    seen.append(v)
    for w in g[v]:
        if w not in seen:
            dfs(g, w, seen)
    return seen

Careful: A version with an explicit stack pops the last neighbor pushed, so it visits in a different order. Without the seen test a cycle recurses until RecursionError.

Taught in Depth-first search

Topological order (DFS)

Also called topological sort, DAG, directed acyclic graph.

Every arrow points forward in the result. A vertex finishes after everything it points to, so finishing order reversed works. A DAG often has many valid orders. O(V+E)⁠.

def visit(g, v, seen, done):
    seen.append(v)
    for w in g[v]:
        if w not in seen:
            visit(g, w, seen, done)
    done.append(v)

def topo(g):
    seen = []
    done = []
    for v in sorted(g):
        if v not in seen:
            visit(g, v, seen, done)
    return done[::-1]

Careful: With a cycle no topological order exists; this version doesn't notice and returns a list that breaks an arrow.

Taught in Topological order

Dijkstra's algorithm

Also called weighted shortest path, relax an edge, least-weight path.

Lists hold (neighbor, weight) pairs; INF = float("inf"). Pop the nearest entry and relax its edges. Out-of-date entries pop later and change nothing. O((V+E)log⁡V) with a binary heap.

def dijkstra(g, start):
    dist = {v: INF for v in g}
    dist[start] = 0
    pq = [(0, start)]
    while pq:
        d, v = heappop(pq)
        for w, wt in g[v]:
            nd = d + wt
            if nd < dist[w]:
                dist[w] = nd
                heappush(pq, (nd, w))
    return dist

Careful: Needs every weight to be zero or more: a negative edge can undercut a vertex already fixed.

Taught in Dijkstra's algorithm

Choosing a graph algorithm

Also called BFS or Dijkstra, which graph search.

Ask what the answer counts and what the edges carry.

The problem asks forAlgorithmCost
Fewest edgesBFSO(V+E)
Least total weight, none negativeDijkstraO((V+E)log⁡V)
An order keeping every arrow forwardTopological orderO(V+E)
Any route, or everything reachableBFS or DFSO(V+E)

Careful: With every weight equal, fewest edges is also least weight, and BFS is enough.

Taught in Which algorithm?

Spanning tree

Also called BFS tree, DFS tree, minimum spanning tree.

A spanning tree joins every vertex of a connected graph with no cycle, using V − 1 edges. The parent links of a search form one; the BFS tree keeps every vertex at its distance from the start. The minimum spanning tree has the least total weight (Prim's or Kruskal's algorithm).

Careful: A minimum spanning tree is not Dijkstra's shortest-path tree: one minimizes the total weight, the other each vertex's distance from the start.

Taught in Trees inside graphs