← All lessons
Algorithms · Lesson 1 of 8

Before you start

This course writes its examples in Python. If you've done Programming basics you can read most of it; this lesson covers the extra shortcuts the code uses, the few data structures it relies on, and what a logarithm is.

Shortcuts. x -= 1 is short for x = x - 1 (and += adds). a, b = 1, 2 sets two variables at once, and a, b = b, a + b works out both right sides first, then stores them. xs[:] is a slice of the whole list: a copy you can change without touching the original. A if test else B picks one of two values in a single line. And for _ in range(3) uses _ as the loop variable's name when the loop doesn't need it.

a, b = 1, 2
a, b = b, a + b
print(a, b)
n = 7
print("odd" if n % 2 else "even")
Prints
2 3
odd

Structures. A set, written {1, 2} or set(), holds each value once and answers x in s almost instantly, however big it is. A stack adds and removes at the same end (last in, first out), like a pile of plates; a Python list does this with append() and pop(). A queue adds at the back and removes from the front (first in, first out), like a line at a shop; deque from collections does this with append() and popleft(). A graph is a set of points (vertices) joined by links (edges), stored here as a dictionary from each vertex to the list of its neighbours.

from collections import deque
q = deque(["A", "B"])
q.append("C")
print(q.popleft())
seen = {"A"}
print("B" in seen)
Prints
A
False

Maths. The logarithm base 2 of n, written log₂ n, is how many times you halve n to get down to 1. Halve 8 three times (8, 4, 2, 1) and you're there, so log₂ 8 is 3. It grows very slowly: log₂ of a thousand is about 10, of a million about 20, of a billion about 30. That slowness is why algorithms that halve their work each step are so fast.

One more idea: when a function calls another function, Python keeps the first one waiting on a stack of unfinished calls, the call stack, and picks it back up when the inner one returns. It matters in the recursion lesson.

Practice

What does this print?

x = 10
x -= 3
x += 1
print(x)
More info

Quick reference

x += 1, x -= 1Add to or take from a variable.
a, b = b, aSet several variables at once (here, a swap).
xs[:]A copy of the whole list.
A if test else BOne of two values, in one line.
set, stack, queueEach value once; last in first out; first in first out.
GraphVertices joined by edges; here a dict of neighbour lists.
log₂ nHow many halvings take n down to 1: about 20 for a million.
Call stackThe calls waiting for the ones they made to return.

The other computer science courses