Python Refresher
Python refreshed — through the lens of one question: how much work does this program do?
- count the basic operations a loop-based program performs
- explain why Euclid's gcd and the √n prime test beat the obvious versions
- handle errors with
try / except - write small classes with
__init__,__str__and__add__
Why efficiency? Counting what the computer does
A program that is correct but slow is useless when the input is large: sorting a billion Aadhaar numbers, searching a database with millions of rows, or running a game that must respond within a few milliseconds. Before we can make programs faster, we need a way to talk about how much work a program does.
The trick is to stop timing programs in seconds (that depends on your laptop) and instead count the basic operations they perform as a function of the input size n. Look at three small programs:
Relate the number of instructions executed to the size of the input, then look for ways to make that number smaller. The first program does constant work, the second grows in step with n, the third grows with n × n.
Doubling n in the two nested loops program makes the number of updates grow by a factor of…
What does this print? (type the exact output)
n = 5
s = 0
for i in range(n):
for j in range(n):
s = s + 1
print(s)Computing gcd — three ways, one huge difference
gcd(m, n) (also called hcf) is the largest k that divides both m and n. For example gcd(8, 12) = 4 and gcd(18, 25) = 1. It always exists, because 1 divides everything. This tiny problem is the perfect laboratory for efficiency.
Attempt 1 — try every candidate
The gcd can't exceed min(m, n), so test every i from 1 to min(m, n) and remember the last (largest) one that divides both. The work is proportional to min(m, n) — fine for small numbers, hopeless for 18-digit ones.
Attempt 2 — use a mathematical fact
If d divides both m and n, say m = a·d and n = b·d, then m − n = (a − b)·d, so d also divides m − n. Therefore gcd(m, n) = gcd(n, m − n). That gives a recursive algorithm that replaces big numbers by smaller ones. But look at gcd(1, 1000): it subtracts 1 a thousand times!
Attempt 3 — Euclid's algorithm
Subtracting n repeatedly from m until the result is smaller than n is exactly what m mod n computes in one step. So: if n divides m, the answer is n; otherwise recurse on (n, m mod n).
Euclid's algorithm needs a number of steps proportional to the number of digits of the larger input — not to its value. That is the difference between 18 steps and 10¹⁸ steps.
What is gcd(84, 36)?
Why is Euclid's algorithm so much faster than the subtraction version?
Prime numbers — checking fewer candidates
A prime has exactly two factors: 1 and itself (so 1 is not prime). The most direct test collects all factors and checks whether the list is exactly [1, n]. We can do much better by asking: how far do we really have to look for a factor?
If n = a × b with both factors larger than √n, then a × b > n — impossible. So every composite number has a factor at most √n. If none of 2…√n divides n, then n is prime.
Two separate savings are visible above: stop early when a factor is found (break / return), and stop at √n. For a prime near a billion, the naive loop runs ~10⁹ times while the √n loop runs about 31,623 times.
What does this program print?
def is_prime(n):
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return n > 1
print([n for n in range(1, 16) if is_prime(n)])To test whether n = 10007 is prime using the √n method, roughly how many values of i must you try at most?
Exception handling — expecting the unexpected
Real programs meet bad input: dividing by zero, converting "abc" to an integer, indexing past the end of a list, reading a missing file. Python signals each of these by raising an exception. If nobody handles it, the program stops with an error message (a traceback).
| Situation | Exception you get |
|---|---|
y = x / z where z == 0 | ZeroDivisionError |
int('abc') | ValueError |
| using a variable that was never assigned | NameError |
L[10] on a list with 3 items | IndexError |
d['missing'] on a dictionary | KeyError |
bad syntax like print(1,,2) | SyntaxError (found before the program even starts) |
You handle an exception with try … except. Python runs the try block; if an error occurs it jumps to the first matching except block; else runs only if there was no error; finally runs always.
What does this program print?
data = [10, 20, 30]
for k in [1, 5, 0]:
try:
print(100 // data[k])
except IndexError:
print("no such index")A try block raises KeyError. Which handler runs?
Classes and objects — building your own data types
Algorithms need data structures, and data structures are built from abstract data types: a way of storing information plus a set of designated functions to manipulate it. For a stack that is: last-in-first-out with push() and pop(). The user of a stack never needs to know how it is stored — the implementation is private; only the specification is public.
A class is the template — it says how data is stored and which functions work on it. An object is one concrete instance created from that template. Point is a class; Point(3, 4) is an object.
Special methods like __init__, __str__ and __add__ (surrounded by double underscores) hook your class into Python's syntax. We will use classes for stacks, queues, linked lists, heaps and trees throughout the course.
What does this program print?
class Counter:
def __init__(self):
self.n = 0
def hit(self):
self.n += 1
return self.n
a = Counter()
b = Counter()
a.hit(); a.hit()
b.hit()
print(a.n, b.n)What does self refer to inside a method?
Measuring time — and why we mostly don't
You can time code with time.perf_counter(). It is useful for sanity checks, but the numbers depend on your hardware, your Python version and what else your computer is doing — so in this course we compare operation counts, which are the same everywhere.
Python limits recursion depth (about 1000 calls by default). Deep recursions such as the subtraction version of gcd raise RecursionError. You can raise the limit with sys.setrecursionlimit(...), but needing to do so is often a sign that an iterative or faster algorithm is a better idea.
Why do we count operations instead of measuring seconds when comparing algorithms?
Chapter challenge — Week 1
Which loop does the most work for large n?
What does this program print?
def gcd(m, n):
a, b = max(m, n), min(m, n)
if a % b == 0:
return b
return gcd(b, a % b)
print(gcd(270, 192))Put the steps of Euclid's algorithm in order.
Which exception does int('12x') raise? (one word)
A student replaces for i in range(2, n) by while i * i <= n in a prime test. What is the main gain?
What does this print? (type the exact output)
def f(n):
c = 0
while n > 1:
n = n // 2
c += 1
return c
print(f(64))In Point(3, 4) + Point(1, 1), which method decides what + does?
Select all statements that are true about exceptions.
Practice on LeetCode
Warm-ups on loops, divisibility, √n tricks and small classes.
Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.
| Problem | Level | Practises | |
|---|---|---|---|
| Fizz Buzz ↗ | Easy | loops and % — operation counting basics | |
| Find Greatest Common Divisor of Array ↗ | Easy | Euclid's algorithm | |
| Greatest Common Divisor of Strings ↗ | Easy | gcd on lengths | |
| Count Primes ↗ | Medium | primes: stop at √n, then the sieve idea | |
| Valid Perfect Square ↗ | Easy | checking up to √n (or halving the range) | |
| Design Parking System ↗ | Easy | a small class with __init__ and a method |
Key takeaways
- Judge algorithms by how the number of operations grows with input size, not by seconds on one machine.
- Euclid's gcd is fast because
modcollapses many subtractions into one step: steps ∝ number of digits, not the value. - A number is prime if no integer in 2…√n divides it; stop early at the first factor.
- Use
try / except / else / finallyto handle runtime errors without crashing. - Classes bundle data with the functions that operate on it — the basis for every data structure we build later.