PDSA Interactive Book
Week 1

Python Refresher

Python refreshed — through the lens of one question: how much work does this program do?

After this chapter you can…
  • 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:

Python · editable
Expected output: 7 45 100
Our goal

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.

Operation counter — choose a loop pattern and see how the count growsInteractive
Check yourself

Doubling n in the two nested loops program makes the number of updates grow by a factor of…

Predict the output

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.

Python · editable
Expected output: (21, 462)

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).

Python · editable
Expected output: (21, 3) (1, 7)

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.

Euclid's trace — compare the three methods on your own numbersInteractive
Check yourself

What is gcd(84, 36)?

Check yourself

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?

Python · editable
Expected output: (True, 95) (True, 8) (False, 998) (False, 1)
Why √n is enough

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.

Python · editable
Expected output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] 10
Predict the output

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)])
Check yourself

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).

SituationException you get
y = x / z where z == 0ZeroDivisionError
int('abc')ValueError
using a variable that was never assignedNameError
L[10] on a list with 3 itemsIndexError
d['missing'] on a dictionaryKeyError
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.

Python · editable
Expected output: (finished one attempt) ratio = 2.5 (finished one attempt) cannot divide by zero (finished one attempt) bad input types
Predict the output

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")
Check yourself

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.

Class vs object

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.

Python · editable
Expected output: (3,4) (5,8) (8,12) 5.0 (4,5)

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.

Predict the output

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)
Check yourself

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 · editable
Recursion depth

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.

Check yourself

Why do we count operations instead of measuring seconds when comparing algorithms?

Chapter challenge — Week 1

…
Check yourself

Which loop does the most work for large n?

Predict the output

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 in order

Put the steps of Euclid's algorithm in order.

Check yourself

Which exception does int('12x') raise? (one word)

Check yourself

A student replaces for i in range(2, n) by while i * i <= n in a prime test. What is the main gain?

Predict the output

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))
Check yourself

In Point(3, 4) + Point(1, 1), which method decides what + does?

Check yourself

Select all statements that are true about exceptions.

Practice on LeetCode

Warm-ups on loops, divisibility, √n tricks and small classes.

How to practise

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.

0 / 6 solvedTick a problem when you have solved it — saved in this browser.
ProblemLevelPractises
Fizz Buzz ↗Easyloops and % — operation counting basics
Find Greatest Common Divisor of Array ↗EasyEuclid's algorithm
Greatest Common Divisor of Strings ↗Easygcd on lengths
Count Primes ↗Mediumprimes: stop at √n, then the sieve idea
Valid Perfect Square ↗Easychecking up to √n (or halving the range)
Design Parking System ↗Easya 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 mod collapses 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 / finally to handle runtime errors without crashing.
  • Classes bundle data with the functions that operate on it — the basis for every data structure we build later.

PDSA Interactive Book · Programming, Data Structures and Algorithms using Python (BSCS2002), IIT Madras BS Degree Programme.
Created by Ammar Hashmi · © 2026. An unofficial study companion — the syllabus follows the official course page and the examples are built around the PDSA Online Textbook; lectures by Prof. Madhavan Mukund (CMI). Always cross-check with the official course material.
Found a mistake or have a suggestion? Report it on GitHub ↗ · Press / to search.