TactivergeOffline

Level 3 Intelligent Robotic Systems · Term 1: Engineering Computation

Programming that scales beyond a single script: modules, objects, structured data, classic algorithms and their cost, numerical methods and honest plots, brought together in a tested route planner.

In this file: 27 lessons across weeks 1–9, with 139 practice questions (questions only, no answers).

Design, model and evaluate simulated robotic systems that integrate computation, the mathematics of motion, perception and feedback, and compare them fairly against alternatives. Levels describe what you can do, not your age. About About 3–4 hours a week: 1.5 hours of lessons, 1–1.5 hours of coding or lab work and 30–60 minutes of analysis and writing..

Week 1: Modular programming

This week you will

One script is not a system

A rover planner works perfectly as one 600-line file. Then you change a unit conversion and three unrelated features break. Why?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Real robot software is hundreds of files written by many people. It stays workable only because each file (a module) does one job and talks to the others through a few well-named functions. When a module breaks, the dependency graph tells you exactly what else might have broken with it.

Goals

Predict

In a planner package, units.py is imported by grid.py and report.py; grid.py is imported by planner.py and io_csv.py; main.py imports io_csv, planner and report. You change units.py. How many other modules could be affected?

  1. Only the two that import it directly
  2. All five modules that import it directly or indirectly
  3. None, if you only changed one function

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Select units.py, then grid.py, then main.py and count the orange modules each time. Which module is safest to change, and which is riskiest? Now tick the shortcut that lets grid.py import planner.py and read the warning.

What the interactive shows, in words

The dependency explorer shows seven modules in layers: units.py at the bottom; grid.py and report.py import units; io_csv.py and planner.py import grid; main.py imports io_csv, planner and report; test_planner.py imports planner and grid. Changing units.py affects all five modules above it. Ticking the shortcut makes grid.py also import planner.py, creating a circular import.

Understand

A module is just a .py file

Any file units.py is a module called units. Another file in the same folder can write import units and call units.cm_to_m(250), or from units import cm_to_m to use the name directly. Python searches the folder of the script you ran first, then the standard library and installed packages.

Interfaces, not internals

Each module should expose a few functions or classes (its interface) and keep its helpers private. By convention, a name starting with an underscore, such as _clamp, is internal. Other modules use only the interface, so you can rewrite the inside freely as long as the interface and its tests still hold.

Arrows only go one way

Draw an arrow from each module to the modules it imports. Good packages form layers: small utility modules at the bottom, the program's entry point at the top, and no loops. A circular import (A imports B and B imports A) means neither can be loaded or tested on its own; fix it by moving the shared code down a layer or the calling code up.

Explain it another way: intuitive

Think of a team building a robot. The motor team promises 'give us a speed in rpm and we will spin at it'. The navigation team doesn't need to know how the motor driver works, only that promise. Modules are those promises written in code.

Explain it another way: technical

import x runs x.py once, caches the module object in sys.modules and binds the name x. Later imports reuse the cache. Code at the top level of a module runs at import time, so modules should mostly define functions and classes, with any script behaviour guarded by if __name__ == "__main__":.

Explain it another way: applied

The Robot Operating System (ROS) splits a robot into packages and nodes with declared dependencies, so a team can rebuild and test only the parts affected by a change. Your four-file planner is the same idea at a smaller scale.

Try these examples

Example 1

Split this conversion out of a planner script into its own module, then use it.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. units.py defines cm_to_m. Which line lets another file call cm_to_m(250) with no prefix?

  • import units
  • from units import cm_to_m
  • import cm_to_m from units
  • include units

2. In a package with no circular imports, which module's changes need the MOST re-testing elsewhere?

  • main.py, the entry point at the top
  • A low-level utility that many modules import
  • A test file
  • It is always the same for every module

3. grid.py imports planner.py so GridMap can call bfs, and planner.py imports grid.py. What is the best fix?

  • Swap the order of the import lines
  • Let main.py call bfs(grid, start, goal), so grid.py no longer imports planner
  • Copy bfs into grid.py as well
  • Put both files' code into one big file

4. planner.py contains def _neighbours_in_bounds(...). What does the leading underscore tell other programmers?

  • The function is faster
  • It is an internal helper, not part of the module's interface
  • Python will refuse to import it
  • It is a constant

5. io_csv.py ends with print(load_map('mars.csv')) at the top level. What happens when planner tests run 'import io_csv'?

  • Nothing, imports never run code
  • The map is loaded and printed during the import, which may fail if mars.csv is missing
  • Python asks which part to run
  • Only the function definitions are copied

Apply it

Take a script you wrote earlier (or the starter planner in the Code Lab) and split it into at least three modules: one for unit conversions, one for loading data and one for the calculation. Draw the dependency arrows on paper. Check there are no loops, and list which modules you would re-test if each one changed.

Reflect

Which module in your split would you protect with the most tests, and why?

Go further (online)

Functions that keep their promises

In 1999 a Mars orbiter was lost because one team's software worked in pound-force seconds and another's expected newton-seconds. What one line of documentation could have helped?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

A function's contract is its promise: give me these inputs, in these units, and I will return this. Teams build on each other's contracts every day. Writing them down, and checking them, turns silent wrong answers into loud, early errors.

Goals

Predict

battery_runtime_h(capacity_mah, current_ma) returns capacity / current. Someone calls it with current_ma = 0. What should a well-designed version do?

  1. Return 0
  2. Return a huge number
  3. Raise a ValueError explaining that current must be positive
  4. Print a warning and carry on

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, write battery_runtime_h with a docstring and a check that both inputs are positive. Call it with good values, then with current_ma = 0 and capacity_mah = -500. Read each error message: does it tell the caller what to fix?

What the interactive shows, in words

The Code Lab activity can be done on paper: write the function's docstring with inputs, units, ranges and return value, then list what it should do for capacity 2200 and current 550 (return 4.0), current 0 (raise ValueError) and capacity −500 (raise ValueError).

Understand

A docstring is the contract

State what each parameter means, its units and allowed range, what is returned (with units), and what happens on bad input. Someone should be able to use the function correctly from the docstring alone, without reading the body.

One job, returned not printed

A function that reads a file, converts units, averages and prints is four functions tangled together. Split it so each does one thing and returns its result. Returned values can be tested, reused and fed into the next step; printed text can only be read by a person.

Fail loudly at the boundary

Check preconditions at the top of the function and raise ValueError("...") with a message that names the bad value. An early, specific error is far cheaper than a wrong number discovered three modules later.

Explain it another way: intuitive

A vending machine has a contract printed on it: insert coins, press a code, get a snack. It rejects foreign coins straight away instead of keeping them and giving you nothing. Good functions behave the same way.

Explain it another way: technical

Preconditions are what must be true of the inputs; postconditions are what the function guarantees about its output. Python's convention is to raise ValueError for a value of the right type but wrong range and TypeError for the wrong type. Type hints such as def f(x: float) -> float document types but are not enforced at run time.

Explain it another way: applied

Flight software standards require every interface to state units and ranges, because many costly failures have come from two correct pieces of code that disagreed about what a number meant.

Try these examples

Example 1

Write a contract-checked runtime function for a robot battery.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Docstring: 'Returns the distance.' What is the most important thing missing for an engineer using it?

  • The author's name
  • The units of the inputs and of the returned distance
  • How long the function took to write
  • A joke

2. Using battery_runtime_h from the worked example, what does battery_runtime_h(3000, 750) return, in hours?

Answer: h

3. Which function design is best for a sensor-log tool?

  • process() reads the file, filters spikes, averages and prints the answer
  • load_log(path), remove_spikes(values, limit) and mean(values), each returning a value
  • One function per line of code
  • A global variable that every function changes

4. wheel_rpm(speed_m_s, diameter_m) is called with diameter_m = -0.1. Which response best keeps the contract?

  • Use abs(diameter) silently
  • raise ValueError('diameter_m must be positive, got -0.1')
  • Return None
  • Return 0

5. A function prints the average current instead of returning it. What can't you do?

  • Read the number on screen
  • Use the average in the next calculation or check it with assert
  • Call the function
  • Give it a docstring

Apply it

Write wheel_rpm(speed_m_s, diameter_m) for a rover: a docstring with units and ranges, checks that raise ValueError for bad inputs, and a returned value. Test it on 0.5 m/s with a 0.12 m wheel (about 79.6 rpm) and on two bad inputs.

Reflect

Think of a number you have computed before without writing its unit. How could it have been misread?

Go further (online)

Tests that catch you before the robot does

Your planner returned a path for six weeks. Then someone added a wall at the map edge and it crashed. Which test would have caught it on day one?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Every module you write is a promise to the rest of the program. Tests are how you check that promise automatically, every time anything changes. They are cheapest to write while you still remember what the function is meant to do.

Goals

Predict

You test mean(values) with [2, 4, 6] and it returns 4. Which extra test is MOST likely to find a bug?

  1. [1, 2, 3]
  2. [10, 20, 30]
  3. An empty list []
  4. [2, 4, 6] again

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, write clamp(value, low, high) and five assert tests: inside the range, below, above, exactly on each limit. Then deliberately break clamp (swap low and high) and run the tests again. How many fail, and do their messages tell you why?

What the interactive shows, in words

The Code Lab activity can be done on paper: write clamp(value, low, high) and work out by hand the expected result for 50, −5, 130, 0 and 100 with limits 0 and 100. Then imagine low and high swapped inside the function and predict which of the five checks fail.

Understand

A test is a hand-worked answer

assert clamp(150, 0, 100) == 100 states an answer you worked out without the code. If the code disagrees, Python raises AssertionError. A good test is small, names what it checks and has a known right answer.

Hunt the edges

Bugs cluster at boundaries: the first and last item, exactly on a limit, empty input, zero, negative numbers, a goal surrounded by walls. For each function, list the edges before you write tests; most of your tests should live there.

Importable modules

Code at the top level runs when a module is imported. Put demos and quick checks under if __name__ == "__main__":. That block runs when you execute the file directly, but not when a test or another module imports it.

Explain it another way: intuitive

A test is like a pre-flight checklist: a list of things that must be true before you trust the aircraft, checked the same way every time.

Explain it another way: technical

Tools such as pytest collect functions named test_* and report each assert that fails along with the values involved. For floating-point results compare with a tolerance: abs(got - want) < 1e-9 or math.isclose(got, want), never ==.

Explain it another way: applied

Safety-critical teams often run thousands of automated tests on every change; a change that breaks one is rejected before it reaches hardware. Your five-line test file is the first step of the same habit.

Try these examples

Example 1

Test a clamp function, including both limits, and keep the demo out of imports.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Which input is the best edge case for a function that returns the last reading of a sensor log?

  • A log with 50 readings
  • A log with exactly one reading, and an empty log
  • A log with 51 readings
  • A log of very large readings

2. Which test is safest for mean([0.1, 0.2]) (true answer 0.15)?

  • assert mean([0.1, 0.2]) == 0.15
  • assert abs(mean([0.1, 0.2]) - 0.15) < 1e-9
  • assert mean([0.1, 0.2])
  • print(mean([0.1, 0.2]))

3. Why put demo code under if __name__ == "__main__":?

  • It makes the code run faster
  • So the demo runs when the file is executed directly but not when it is imported
  • Python requires it in every file
  • It hides the code from other programmers

4. assert clamp(-5, 0, 100) == 0 fails with clamp returning 100. What is the most likely bug?

  • The test is wrong
  • low and high are swapped somewhere inside clamp
  • Python's max function is broken
  • Negative numbers can't be clamped

5. Which set of tests gives the most confidence for clamp(value, low, high)?

  • One test with a typical value
  • Inside, below, above, exactly on each limit, and low > high raising ValueError
  • Ten tests all inside the range
  • No tests, because the code is short

Apply it

For your wheel_rpm or battery_runtime_h function, write a test function with at least five asserts: two normal values worked by hand, one boundary and two that check a ValueError is raised (use try/except and assert inside it). Guard any demo code with if __name__ == "__main__":.

Reflect

Which edge case surprised you most, either because it broke your code or because you hadn't thought of it?

Go further (online)

Week 2: Object-oriented programming

This week you will

One blueprint, many sensors

A robot has six identical range sensors, each with its own offset and its own readings. Do you write six sets of variables, or one blueprint?

About 40 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Engineering software is full of things that come in many copies: sensors, motors, parts, waypoints. A class describes the kind of thing once; each object is one real copy with its own state. That keeps six sensors from accidentally sharing one list of readings.

Goals

Predict

A class puts readings = [] on the class body instead of inside __init__. You record 50 cm on the front sensor. What does the rear sensor's readings list contain?

  1. [] (it is empty)
  2. [52] (the front sensor's reading)
  3. An error

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Record a few readings on front and rear, then compare vars(front) and vars(rear). Call rear.mean() before it has readings and read the error. Now tick the bug toggle and record on front only: what happened to rear?

What the interactive shows, in words

The inspector shows a RangeSensor class with a front sensor (offset 2 cm) and a rear sensor (offset −1 cm). Recording 50 cm on the front stores 52 in front's own list only. With the bug toggle on, readings live on the class, so the same 52 appears in both sensors' readings.

Understand

Class, instance, self

class RangeSensor: defines a new type. front = RangeSensor("front", 2) calls __init__ to build one instance. Inside each method, self is the particular object the method was called on, so self.readings means this sensor's readings.

Attributes live on the object

Assigning self.offset_cm = offset_cm stores a value on that one object; vars(front) shows them. Python looks up an attribute on the object first, then on its class. Constants that every instance shares, like unit = "cm", can sit on the class.

The shared-list trap

A list (or dict) written in the class body exists once, for every instance. Appending through self.readings changes that one shared list, so every sensor sees every reading. Create mutable state inside __init__ so each object gets its own.

Explain it another way: intuitive

A class is like a part drawing; instances are the parts made from it. Every bracket made from one drawing has the same shape, but each has its own serial number and its own scratches.

Explain it another way: technical

Instances store attributes in a per-object namespace (obj.__dict__). Attribute lookup checks the instance, then the class, then base classes. A method call front.record(50) is shorthand for RangeSensor.record(front, 50), which is where self comes from.

Explain it another way: applied

Robot drivers commonly define one class per device type (an IMU, a lidar, a motor controller) and create one object per physical device, each holding its own port, calibration and latest data.

Try these examples

Example 1

Model a range sensor with a calibration offset, record readings and report their mean.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Using RangeSensor from the worked example, s = RangeSensor('left', 3); s.record(40); s.record(46). What does s.mean() return?

Answer: cm

2. Inside record(self, raw_cm), what is self when you call rear.record(80)?

  • The RangeSensor class
  • The rear object
  • The number 80
  • A copy of front

3. Which class definition gives each sensor its own readings list?

  • readings = [] in the class body
  • self.readings = [] inside __init__
  • global readings
  • readings = [] inside record

4. RangeSensor.unit = "cm" is a class attribute. After front = RangeSensor('front', 2), what is front.unit?

  • 'cm', found on the class
  • An AttributeError, because __init__ never set it
  • None

5. rear = RangeSensor('rear', -1); rear.mean() is called before any readings. With the worked example's code, what happens?

  • Returns 0
  • Raises ValueError('rear has no readings yet')
  • Returns -1
  • Raises ZeroDivisionError

Apply it

Write a Part class for a stores inventory with attributes part_no, description, mass_g and quantity, a method total_mass_kg() and a method withdraw(n) that refuses (raises ValueError) to go below zero. Create three parts and print the total mass of everything in stock.

Reflect

Where in your own code have you used several parallel lists (names, offsets, readings) that would be clearer as one list of objects?

Go further (online)

Objects that guard their own limits

A motor is rated to 3,000 rpm. Fifteen different parts of the code set its speed. How do you make sure none of them ever asks for 3,500?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

An invariant is a rule that must always be true for an object: speed never exceeds the rating, stock never goes negative. If every change goes through methods that enforce the rule, you only have to get it right in one place.

Goals

Predict

Motor has max_rpm = 3000 and a method set_speed(rpm) that clamps to [0, max_rpm]. Somewhere, code writes motor.rpm = 3500 directly. What is motor.rpm afterwards?

  1. 3000, because the class clamps it
  2. 3500, because the direct assignment bypassed set_speed
  3. An error

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, build the Motor class from the worked example. Call set_speed with 1500, 4000 and −200 and print speed each time. Then write motor._rpm = 9999 directly and print again. Add a test that would catch the bypass in a code review.

What the interactive shows, in words

The Code Lab activity can be done on paper: a Motor rated 3000 rpm receives requests 1500, 4000 and −200 through set_speed and reports 1500, 3000 and 0. Assigning to the read-only rpm property raises AttributeError, while writing to the internal _rpm attribute bypasses the rule, which is why the convention and tests matter.

Understand

State changes go through methods

A Motor stores its speed in self._rpm. The method set_speed(rpm) clamps the request and is the only intended way in. Every caller gets the safety rule for free, and if the rule changes you edit one method.

Read through a property

Python's @property lets callers read motor.rpm like an attribute while it is really a method. Without a setter, motor.rpm = 3500 raises AttributeError, so the invariant can't be bypassed by accident through the public name.

Test the rule, not the code

Write tests from the invariant: after any sequence of calls, 0 ≤ rpm ≤ max_rpm. Test inside, both limits, above, below and a negative request. These tests stay valid however you rewrite the inside of the class.

Explain it another way: intuitive

A thermostat lets you turn the dial, but the boiler has its own safety cut-out that you can't set past. Methods are the dial; the invariant is the cut-out.

Explain it another way: technical

Python has no truly private attributes. A single leading underscore signals 'internal'; @property creates read-only access; a @rpm.setter could validate assignments instead. Encapsulation in Python is a contract between programmers, backed by tests.

Explain it another way: applied

Motor controller firmware enforces current and speed limits inside the driver itself, not in every piece of code that requests motion, so a bug elsewhere can't overdrive the motor.

Try these examples

Example 1

A motor object that can never be set outside its rating.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. With the worked example's Motor('arm', 2400), what does set_speed(2650) return?

Answer: rpm

2. Which is an invariant for an inventory Part object?

  • quantity is always ≥ 0
  • quantity changed recently
  • The class has three methods
  • description is printed in capitals

3. Motor defines rpm with @property and no setter. What does m.rpm = 3500 do?

  • Sets the speed to 3500
  • Clamps to max_rpm
  • Raises AttributeError
  • Silently does nothing

4. part.withdraw(5) is called when quantity is 3. What should a well-designed method do?

  • Set quantity to -2
  • Set quantity to 0 and say nothing
  • Raise ValueError and leave quantity at 3
  • Delete the part

5. Which test best checks Motor's invariant?

  • assert m.set_speed(1500) == 1500 only
  • Call set_speed with values below, inside, on and above the limits and assert 0 <= m.rpm <= m.max_rpm after each
  • Print m.rpm and look at it
  • Check that the class has a method called set_speed

Apply it

Finish the inventory Part class: quantity is read through a property, withdraw(n) and restock(n) refuse invalid requests, and a test function tries at least six sequences of calls and asserts quantity ≥ 0 after each.

Reflect

Name a rule in a machine you know that should be enforced in one place rather than trusted to every user.

Go further (online)

Object or function? Choosing the clearer design

Converting degrees to radians, modelling a robot arm with three motors, parsing one line of a CSV file: which of these deserves a class?

About 30 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Classes are a tool, not a goal. A good engineer reaches for one when data and behaviour belong together and there's state to protect, and writes a plain function when the job is just input → output. Choosing well keeps code short and obvious.

Goals

Predict

Which of these is the best candidate for a class?

  1. deg_to_rad(deg): one formula
  2. A grid map that stores cells, knows which are walls and lists a cell's neighbours
  3. Adding two numbers

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, start from the GridMap class in the worked example. Load the small map, print neighbours((0, 0)) and neighbours((1, 1)), then add a method is_free(cell). Would a set of plain functions taking the grid as a parameter be any less clear?

What the interactive shows, in words

The Code Lab activity can be done on paper: draw the 3 × 3 map with rows '..#', '...', '#..'. For cells (0, 0) and (1, 1), list the free neighbours up, right, down and left: (0, 0) has (0, 1) and (1, 0); (1, 1) has (0, 1), (1, 2), (2, 1) and (1, 0).

Understand

Signs that you want a class

Several functions all take the same bundle of data; there's a rule the data must keep; you need many copies with their own state; or you want to swap one implementation for another behind the same methods (two kinds of sensor with the same read()).

Signs that a function is enough

The task is a calculation from inputs to an output with no memory between calls: unit conversions, a mean, a distance between two points. Wrapping these in a class adds ceremony and hides nothing worth hiding.

Composition: objects made of objects

A Robot can have a list of Motor objects and a RangeSensor. Each part keeps its own rules; the robot coordinates them. This 'has-a' structure mirrors real machines and is usually simpler than deep inheritance.

Explain it another way: intuitive

A calculator button is a function: press it, get an answer. A thermostat is an object: it remembers a setpoint and the current temperature, and its buttons change that memory.

Explain it another way: technical

Classes bundle state with behaviour and give you a namespace, encapsulation and polymorphism (different classes, same method names). Their cost is indirection. Pure functions are easiest to test because the same inputs always give the same output.

Explain it another way: applied

Path-planning libraries usually model the map as an object (it has state and a query interface) but the search algorithms as functions that take the map as a parameter, so one planner works on any map that provides neighbours() and cost().

Try these examples

Example 1

A grid map class with a small interface that a planner can use.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. mm_to_inches(mm) converts a length. Class or function?

  • A class, so it can be extended later
  • A plain function: one input, one output, no state
  • A global variable

2. Using the worked example's GridMap with rows ['..#', '...', '#..'], how many neighbours does cell (2, 2) have?

Answer: cells

3. A Robot holds two Motor objects and a RangeSensor. What is this design called?

  • Inheritance
  • Composition (a robot has motors)
  • Recursion
  • A circular import

4. Which situation most strongly suggests writing a class?

  • Five functions all take the same (cells, width, height) arguments and must agree on what a wall is
  • A function that squares a number
  • A loop that runs ten times
  • A single print statement

5. Why might bfs(grid, start, goal) be a function rather than a GridMap method?

  • Functions are always faster
  • So the same planner works on any map object that provides neighbours(), and the map stays small
  • Methods can't take parameters
  • Python forbids methods that return lists

Apply it

Sketch the design for the term project: which classes (if any) and which functions will you need? For each, write one sentence justifying the choice and list its public interface. Then implement GridMap with in_bounds, is_wall, neighbours and a from_text(text) helper, plus three tests.

Reflect

Describe one piece of code where you'd now choose a function over a class (or the other way round), and why.

Week 3: Lists and structured data

This week you will

Slice, filter, transform: lists at speed

A wheel encoder logs 10,000 speeds. You need the last minute, every tenth sample, and only the readings above 20 cm/s. Can you do each in one line?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Sensor logs, part lists and paths are all lists. Slicing and comprehensions let you say exactly which part of the data you want, in a line that is easy to read and hard to get subtly wrong.

Goals

Predict

readings = [12, 15, 11, 18, 22, 19, 25, 21]. What is readings[1:6:2]?

  1. [15, 18, 19]
  2. [15, 11, 18, 22, 19]
  3. [12, 11, 22]
  4. [15, 18, 19, 21]

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In List + slicing mode, predict each result before you type it: readings[2:5], readings[-3:], readings[::3], readings[::-1], readings[5:1:-2]. Then try a step of 0. Which prediction did you get wrong, and why?

What the interactive shows, in words

The list visualiser shows readings = [12, 15, 11, 18, 22, 19, 25, 21] with each index from 0 to 7 (and −8 to −1). Typing start, stop and step highlights the chosen items: 1, 6, 2 selects 15, 18 and 19; a negative step walks backwards; a step of 0 gives a ValueError.

Understand

Indexes count gaps, from zero

readings[0] is the first item, readings[-1] the last. A slice a[start:stop] includes start and stops before stop, so a[0:3] has exactly 3 items and a[:k] + a[k:] is always the whole list. Out-of-range slice ends are clipped, but out-of-range single indexes raise IndexError.

Steps and reversing

A third number is the step: a[::10] is every tenth sample (decimation), a[::-1] is the list reversed. With a negative step the defaults flip: start from the end and walk backwards. A step of 0 is an error.

Comprehensions

[v for v in readings if v > 20] filters; [v / 100 for v in readings] transforms (cm/s to m/s); you can do both at once. A comprehension builds a new list and leaves the original untouched, which makes it safer than editing a list while looping over it.

Explain it another way: intuitive

Think of fence posts with the gaps numbered: a slice [2:5] takes the fence panels between post 2 and post 5. That's 5 − 2 = 3 panels.

Explain it another way: technical

Slicing creates a new list (a shallow copy) in time proportional to its length. len(a[s:e]) is max(0, e - s) after clipping to [0, len(a)]. Comprehensions are evaluated left to right like the equivalent for-loop with an if and an append, but are more compact.

Explain it another way: applied

Telemetry tools routinely decimate (keep every n-th sample) to plot long logs quickly, and keep the most recent window (a[-600:] for the last minute at 10 Hz) for live displays.

Try these examples

Example 1

From a 10 Hz speed log in cm/s, take the last 2 seconds, convert to m/s and keep only readings above 0.2 m/s.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A wheel encoder log is readings = [1, 53, 98, 96, 28, 61, 72, 43, 99]. What does sum(readings[3:4]) evaluate to?

Answer:

2. A log has 3,000 samples at 50 Hz. Which slice gives the last 10 seconds?

  • log[-10:]
  • log[-500:]
  • log[2500:2999]
  • log[:500]

3. Which comprehension gives the masses (kg) of parts heavier than 0.5 kg, from masses_g in grams?

  • [m / 1000 for m in masses_g if m > 500]
  • [m for m in masses_g if m / 1000]
  • [m > 500 for m in masses_g]
  • [m / 1000 if m > 500 for m in masses_g]

4. A wheel encoder log is readings = [67, 75, 95, 45, 62, 53, 2, 53]. What does len(readings[0:5:2]) evaluate to?

Answer:

5. path has 8 waypoints. Which expression raises IndexError?

  • path[7]
  • path[-8]
  • path[8]
  • path[5:20]

Apply it

Write a function window_stats(readings, rate_hz, seconds) that returns the min, mean and max of the most recent window. Test it on a short list where you can work the answer by hand, including a window longer than the log.

Reflect

Which slicing rule do you expect to trip over most, and what trick will you use to remember it?

Go further (online)

From CSV file to records you can query

A test rig writes a CSV with a header row and 2,000 lines. How do you ask 'which runs drew more than 1.5 A?' without counting columns by hand?

About 40 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Most engineering data arrives as text tables: test-rig logs, inventories, sensor exports. Turning each row into a dictionary keyed by column name makes every later question readable and robust to someone adding a column.

Goals

Predict

csv.DictReader reads the row 'run,current_a' / '3,1.72'. What is type(row['current_a'])?

  1. float
  2. int
  3. str
  4. dict

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, paste the worked example. Run it, then add a row with an empty current and one with 'n/a'. Make the loader skip bad rows but count them, and print how many were skipped.

What the interactive shows, in words

The Code Lab activity can be done on paper: from the five-row log, motor A has currents 1.20 and 1.31 (mean 1.255 A) and motor B has 1.72 and 1.66 (mean 1.69 A); run 4 has an empty current and is skipped and counted.

Understand

Rows as dictionaries

csv.DictReader uses the header row as keys, so each row becomes {"run": "3", "motor": "B", "current_a": "1.72"}. Code that says row["current_a"] keeps working if someone inserts a new column; code that says row[2] silently reads the wrong one.

Text in, numbers out, carefully

Every field is a string. Convert with int() or float() inside a try block, and decide a policy for bad values: skip and count them, or stop with an error naming the line. Never let a bad row quietly become 0.

Group with a dictionary

To summarise by category, build a dict of lists: by_motor.setdefault(row["motor"], []).append(current). Then each key's list can be averaged or counted. Dictionaries are the natural shape for 'one answer per name'.

Explain it another way: intuitive

A CSV is a spreadsheet saved as plain text. DictReader is like reading each row while keeping your finger on the header, so you always know which number is which.

Explain it another way: technical

csv handles quoting and commas inside fields, which a naive line.split(",") gets wrong. io.StringIO lets you test a loader on a string instead of a real file. Opening files with newline="" is the documented way to let the csv module handle line endings.

Explain it another way: applied

Test engineers often keep raw rig logs untouched and write loaders that report how many rows were rejected and why, so the cleaning step is visible in the final report.

Try these examples

Example 1

Load a motor test log, skip bad rows, and average current per motor.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. row = {'run': '4', 'current_a': '1.5'} from DictReader. What does row['run'] + 1 do?

  • Returns 5
  • Returns '41'
  • Raises TypeError: can only concatenate str to str
  • Returns 4.0

2. In the worked example, if the empty current for run 4 is fixed to 1.75, what is motor B's average current (3 decimal places)?

Answer: A

3. Some rows have current 'n/a'. Which policy is best for an engineering report?

  • Treat them as 0 A
  • Skip them, count them, and state the count in the report
  • Delete the CSV and start again
  • Replace them with the average so the chart looks complete

4. Which line adds current to a per-motor list, creating the list the first time a motor appears?

  • by_motor[motor] = current
  • by_motor.setdefault(motor, []).append(current)
  • by_motor.append(motor, current)
  • by_motor[motor].append(current)

5. A log of motor temperature (°C) reads xs = [42, 50, 49, 47, 47, 44, 43, 44, 47]. What is the mean, statistics.mean(xs)? Give 2 decimal places.

Answer:

Apply it

Write a loader for a part inventory CSV (part_no, description, qty, mass_g) that returns a list of dicts and a count of rejected rows. Use it to answer: which parts have qty below 10, and what is the total mass in stock in kg? Test the loader on a string containing at least one bad row.

Reflect

Why is it important that your report says how many rows were skipped?

Go further (online)

Module check: the stores audit

The robotics lab's stores list says 120 M3 bolts. The shelf has 96. Your job: write the program that finds every mismatch before the next build day.

About 45 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

This module check brings weeks 1–3 together on a task real labs do: reconcile what the records say with what is actually on the shelf. It needs clean structure, careful data handling and honest reporting.

Goals

Predict

You have the recorded stock as a dict {part_no: qty} and the shelf count as another dict. What is the clearest way to find parts missing from the shelf count entirely?

  1. Loop over both dicts comparing every pair
  2. Set difference: recorded.keys() - counted.keys()
  3. Sort both and compare by index

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, build the audit: a stock.py module with a load function, a Part class (or plain dicts: justify your choice), and an audit(recorded, counted) function that returns missing, unexpected and mismatched parts. Run it on the worked example's data, then add three tests.

What the interactive shows, in words

The Code Lab activity can be done on paper: recorded stock {M3-BOLT 120, M3-NUT 340, BRG-608 16, SERVO-9G 6} and shelf count {M3-BOLT 96, M3-NUT 340, BRG-608 14, BELT-GT2 3}. Missing: SERVO-9G. Unexpected: BELT-GT2. Mismatched: M3-BOLT (24 short), BRG-608 (2 short).

Understand

Plan the pieces first

Loading (text → records), comparing (two dicts → differences) and reporting (differences → readable text) are three jobs. Give each its own function, keep loading separate from comparing so you can test the comparison on hand-made dicts.

Sets for 'which keys', dicts for 'how many'

recorded.keys() - counted.keys() finds parts never counted; the reverse finds surprises on the shelf; recorded.keys() & counted.keys() gives parts in both, whose quantities you then compare.

Report like an engineer

Sort the output, give units, and lead with what matters: the biggest shortfalls first. Say how many rows were rejected when loading. A short note on design choices (why a dict, why a class or not) is part of the deliverable.

Explain it another way: intuitive

It's a spot-the-difference puzzle between two lists. Sorting both sides into labelled boxes (dicts) makes the differences jump out.

Explain it another way: technical

Set operations on dict key views are O(len) on average, compared with O(n·m) for nested loops. Returning plain data (lists of tuples) from audit() keeps it testable; formatting happens in a separate report function.

Explain it another way: applied

Stock reconciliation is a standard task in workshops and factories; the same pattern (keys only in A, only in B, in both with different values) is used to compare configuration files, parts lists and sensor calibration tables.

Try these examples

Example 1

Audit recorded stock against a shelf count.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. recorded has keys {A, B, C}; counted has keys {B, C, D}. What is recorded.keys() - counted.keys()?

  • {A}
  • {D}
  • {A, D}
  • {B, C}

2. In the worked example, how many M3 bolts are missing from the shelf compared with the record?

Answer: bolts

3. Which structure makes audit() easiest to test?

  • audit() reads the files, compares and prints
  • audit() takes two dicts and returns lists; loading and printing are separate functions
  • audit() uses global variables set by the loader
  • All code in one long script with no functions

4. A log of motor temperature (°C) reads xs = [63, 66, 59, 62, 60, 54, 60]. What is the median, statistics.median(xs)? Give 2 decimal places.

Answer:

5. A wheel encoder log is readings = [45, 5, 63, 55, 46, 46, 16, 12, 19, 44]. What does readings[2] evaluate to?

Answer:

6. Which report line is most useful to the lab manager?

  • 'Some parts are wrong.'
  • 'M3-BOLT: recorded 120, counted 96 (24 short)' listed first because it is the largest shortfall
  • A printout of both dicts
  • 'Audit complete.'

Apply it

Module check deliverable. A small package with stock.py (loading, with a rejected-row count), audit.py (comparison) and main.py (report), at least six tests (including empty and identical inputs), and a 150-word note: why you chose dicts, whether a Part class helped, and what your report puts first.

Reflect

Which part of weeks 1–3 (modules, classes, lists, dicts) made this task easiest, and which do you need to practise?

Go further (online)

Week 4: Data structures

This week you will

List, tuple, set or dict? Pick the right container

Checking whether a part number is in a list of 100,000 parts takes up to 100,000 comparisons. With a set it takes about one. What changed?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

The container you choose decides how fast your program can answer its most common question. Pick a list when order matters, a set when you ask 'have I seen this?', a dict when you ask 'what is the value for this key?', and a tuple for a small fixed record like a cell (row, col).

Goals

Predict

A route planner must check 'have I already visited this cell?' thousands of times. Which container should hold the visited cells?

  1. A list
  2. A set of (row, col) tuples
  3. A string
  4. A list of lists

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Open Dict (inventory) mode and look up each part. Note how many names a list scan would have to compare. Look up the part that isn't stocked: what happens with [] and with .get()? Then switch to List mode and compare.

What the interactive shows, in words

The dict mode shows an inventory of six parts. Looking up 'servo SG90' returns 6 directly; as a list of pairs a scan would compare 4 names. Looking up an unstocked 'M4 bolt' raises KeyError with square brackets but returns 0 with .get(key, 0); a list scan would check all 6 names.

Understand

Four containers, four questions

list: ordered, indexable, may repeat; 'what is the 5th reading?'. tuple: like a list but fixed, perfect for a record such as (row, col). set: unordered, no repeats; 'is this in the collection?'. dict: keys mapped to values; 'what is the stock of this part?'.

Why sets and dicts are fast

A set or dict computes a hash of the key, which says roughly where to look, so x in s and d[k] take about the same time whether there are 10 items or 10 million (on average). x in some_list compares items one by one: up to n comparisons.

Keys must not change

Only immutable values can be set members or dict keys: numbers, strings and tuples of them. That is another reason to store a cell as the tuple (3, 7) rather than the list [3, 7]. Lists can't be hashed, so {[3, 7]} raises TypeError.

Explain it another way: intuitive

A list is a queue of people you check one by one; a dict is a cloakroom where your ticket number takes you straight to your coat.

Explain it another way: technical

Average costs: list index O(1), list membership O(n), append O(1) amortised, insert at the front O(n); set/dict membership, insert and lookup O(1) on average. The price is memory and no ordering by value (dicts do keep insertion order in Python 3.7+).

Explain it another way: applied

Path planners keep the visited set as a hash set of cell tuples and the best-known cost per cell as a dict; switching a visited list to a set is often the single biggest speed-up in a student planner.

Try these examples

Example 1

Store visited cells and per-cell costs for a planner.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. You need the stock quantity for any part number, looked up thousands of times. Which container?

  • A list of quantities
  • A dict {part_no: qty}
  • A set of part numbers
  • A tuple of tuples, scanned each time

2. visited = set(); visited.add([3, 7]). What happens?

  • The cell is added
  • TypeError: unhashable type: 'list'
  • The set becomes [3, 7]
  • Two items, 3 and 7, are added

3. A list holds 50,000 part numbers in random order. Checking a part that is NOT in the list: how many comparisons does 'p in parts' make?

Answer: comparisons

4. A planned path must keep its waypoints in order and may visit the same waypoint twice. Which container?

  • set
  • list
  • dict
  • Nothing built in can do this

5. stock = {'M3-BOLT': 120}. What does stock.get('M4-BOLT', 0) return?

  • KeyError
  • 0
  • None
  • 120

Apply it

Rewrite a planner's visited list as a set and its distance list as a dict keyed by cell tuples. On a 100 × 100 open grid, count how many membership comparisons the list version would make in total (sum the list length at each check) and compare with one lookup per check for the set.

Reflect

Which question does your current project ask most often, and which container answers it fastest?

Go further (online)

Stacks and queues: who goes next?

A robot cell gets jobs faster than it can do them. Do you serve the newest job first, or the oldest? The answer changes everything.

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Many systems are really about order: undo histories, job queues, sensor event buffers, and the search frontier of a path planner. A stack serves the newest item first (LIFO); a queue serves the oldest (FIFO). Picking the wrong one is a fairness bug, or a planner that wanders.

Goals

Predict

A queue receives jobs 101, 102, 103, then serves one job, then receives 104. Which job is served next?

  1. 101
  2. 102
  3. 103
  4. 104

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In Stack mode, append three values and pop twice: which came out? Do the same sequence in Queue mode. Then pop from an empty structure and read the error. Which one would you use for an undo button, and which for print jobs?

What the interactive shows, in words

The stack and queue modes show items in a row, oldest on the left. In a stack, append adds to the right and pop removes from the right (newest). In a queue, append adds to the right and popleft removes from the left (oldest). Popping from an empty structure shows IndexError.

Understand

Stack: last in, first out

A Python list is a stack: s.append(x) pushes onto the top, s.pop() removes and returns the top. Both are fast (O(1)). Use it for undo, for backtracking, and for depth-first search.

Queue: first in, first out

from collections import deque gives a double-ended queue. q.append(x) joins the back; q.popleft() serves the front, both in O(1). Don't use list.pop(0) for a queue: it shifts every remaining item, which is O(n).

Empty means stop

Popping from an empty list or deque raises IndexError. Loops usually run while q: (an empty container is falsy), so they end naturally when the work is done.

Explain it another way: intuitive

A stack is a pile of plates: you take the top one. A queue is a line at a bus stop: the person who arrived first boards first.

Explain it another way: technical

deque is implemented as a linked list of blocks, so both ends are O(1). A list is a dynamic array: the end is O(1) amortised, but inserting or removing at the front moves every element.

Explain it another way: applied

Robot task schedulers use FIFO queues for fairness; motion planners use stacks to backtrack out of dead ends; breadth-first search (next lesson) is simply 'keep the frontier in a queue'.

Try these examples

Example 1

Process jobs in arrival order and keep an undo history.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A robot cell queues jobs in arrival order: from collections import deque; q = deque(); q.append(27); q.append(49); q.popleft(); q.append(37); q.popleft(). What value does the final q.popleft() return?

Answer:

2. An editor's undo button should reverse the most recent change first. Which structure?

  • A queue
  • A stack
  • A set
  • A dict

3. Why use deque.popleft() instead of list.pop(0) for a long job queue?

  • pop(0) returns the wrong item
  • pop(0) shifts every remaining item, so it gets slower as the list grows; popleft() is O(1)
  • deque uses less memory in all cases
  • list.pop(0) doesn't exist

4. An editor keeps an undo stack of waypoint ids: s = []; s.append(38); s.append(23); s.append(27); s.pop(); s.append(33); s.pop(); s.append(3); s.pop(). What value does the final s.pop() return?

Answer:

5. What does 'while q:' do when q is an empty deque?

  • Runs forever
  • Skips the loop body, because an empty deque is falsy
  • Raises IndexError
  • Waits for an item

Apply it

Simulate a robot cell: jobs arrive at known times and each takes a known number of minutes. Use a deque to serve them in order and record each job's waiting time. Then try a stack instead and compare the longest wait. Which is fairer, and when might the stack be acceptable?

Reflect

Name one system you use that is a queue and one that is a stack.

Go further (online)

Breadth-first search: a queue explores a map

Put a robot in a maze and flood it outwards one step at a time. Why does the first time the flood touches the goal give the shortest route?

About 45 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Breadth-first search (BFS) is the simplest planner that is guaranteed to find a route with the fewest moves. It's also a perfect showcase for this week: a deque for the frontier, a set for visited cells, a dict for how you got to each cell.

Goals

Predict

On an open 5 × 5 grid (moves up, down, left, right), how many moves does BFS's path take from the top-left corner to the bottom-right?

  1. 5
  2. 8
  3. 10
  4. 25

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Keep Breadth-first search selected and step through the first 20 expansions. Notice the 'rings' of equal move count. Then wall off the goal completely and watch what BFS does. Finally, add walls to make the path as long as you can.

What the interactive shows, in words

The planner shows a 7 × 10 grid with a start on the left and a goal on the right, a wall in column 5 rows 1 to 5, and a rough patch. BFS expands cells in rings of increasing move count and returns a fewest-moves path around the end of the wall. Walling off the goal makes BFS expand every reachable cell and report no path.

Understand

The frontier is a queue

Start with the start cell in a queue. Repeatedly take the oldest cell, and add each unvisited free neighbour to the back. Because cells come out in the order they went in, every cell 1 move away is processed before any cell 2 moves away, and so on.

Visited set and came-from dict

Mark a cell visited when you add it to the queue, so it is never queued twice. Record came_from[neighbour] = current. When you reach the goal, follow came_from back to the start and reverse: that's the path.

Guarantees and limits

BFS always finds a path with the fewest moves if one exists, and reports failure after visiting every reachable cell if not. It ignores terrain cost: a short path through mud beats a long path on tarmac. Fixing that is Dijkstra's job in the term project.

Explain it another way: intuitive

Drop ink at the start. It spreads one cell further each tick. The first tick it reaches the goal tells you the shortest number of moves, and the way the ink arrived is the path.

Explain it another way: technical

Each cell is enqueued at most once and each edge is checked a constant number of times, so BFS on a grid with V cells runs in O(V) time and uses O(V) memory for the queue, visited set and came-from dict.

Explain it another way: mathematical

Let d(v) be the true fewest-moves distance. By induction, BFS dequeues all cells with d = k before any with d = k + 1, because each is enqueued by a cell at distance k − 1. So the first time the goal is dequeued its recorded path has length d(goal).

Explain it another way: applied

Warehouse robots and game characters on tile maps often use BFS (or its weighted relatives) to plan around shelves and walls many times a second.

Try these examples

Example 1

BFS on a text map, returning the path as a list of cells.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. On an open 6-row × 9-column grid, BFS plans from (0, 0) to (5, 8). How many moves are in its path?

Answer: moves

2. What would change if BFS used a stack (pop the newest cell) instead of a queue?

  • Nothing
  • It would become depth-first search: it still explores, but the first path found need not be the shortest
  • It would find shorter paths
  • It would crash

3. Why mark a cell visited when it is ADDED to the queue, rather than when it is taken out?

  • It looks neater
  • Otherwise the same cell can be queued many times by different neighbours, wasting time and memory
  • Python requires it
  • So the path is reversed

4. The goal is completely surrounded by walls. What does BFS do?

  • Loops forever
  • Visits every cell reachable from the start, empties the queue and reports no path
  • Walks through the wall
  • Returns the start cell

5. A robot cell queues jobs in arrival order: from collections import deque; q = deque(); q.append(3); q.append(28); q.append(23); q.popleft(); q.popleft(); q.popleft(); q.append(23); q.popleft(). What value does the final q.popleft() return?

Answer:

Apply it

Implement bfs as a function that takes a GridMap object (from week 2) and uses only its neighbours() method. Test it on a corridor, a map that forces a detour, and a map with an unreachable goal. Count how many cells it expands on an open 20 × 20 grid from corner to corner.

Reflect

Why is it useful that BFS 'fails' cleanly when there is no path? What could happen in a robot if it didn't?

Week 5: Search and sorting

This week you will

Insertion sort: tidy as you go

Parts come off a line nearly in order of mass, with the odd one out of place. Which simple sort hardly has to do any work at all?

About 40 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Sorting is everywhere: ranking test runs, ordering waypoints, preparing data for binary search. Insertion sort is how most people sort a hand of cards, and it has a superpower: on data that's already nearly sorted it is extremely fast.

Goals

Predict

Insertion sort and selection sort race on an already sorted list of 10 items. Which makes fewer comparisons?

  1. Insertion sort
  2. Selection sort
  3. They tie

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Race the two sorts on each input order. Record the total comparisons for n = 8 in a table: shuffled, nearly sorted, sorted, reversed. When does insertion sort tie with selection sort? Check the n − 1 and n(n − 1)/2 rules.

What the interactive shows, in words

The sorting race shows two bar charts of the same input, one for insertion sort and one for selection sort, with a running comparison count. For n = 8: sorted input costs insertion sort 7 comparisons and selection sort 28; reversed input costs both 28; shuffled input usually costs insertion sort noticeably fewer.

Understand

Grow a sorted part on the left

Treat a[0] as sorted. Take the next item (the key) and shift bigger items in the sorted part one place right until you meet one that isn't bigger, then drop the key in the gap. Repeat for every item. The sorted part grows by one each pass.

Counting comparisons

Each comparison is one test of a[j] > key. A key passes over every bigger item to its left, plus one more comparison where it stops (unless it reaches the front). Sorted input: 1 comparison per key, n − 1 in total. Reversed: every key travels to the front, 1 + 2 + … + (n − 1) = n(n − 1)/2.

Stable and in place

Insertion sort never moves equal items past each other (it is stable), and it needs no extra list (it is in place). It is quadratic in the worst case, so for big shuffled data you'd use Python's built-in sorted(), which is O(n log n).

Explain it another way: intuitive

Sort a hand of cards by picking up one at a time and sliding it left into place among the cards you already hold.

Explain it another way: technical

Best case O(n), worst and average case O(n²) comparisons and moves. The number of shifts equals the number of inversions (pairs that are out of order), so it is fast whenever inversions are few.

Explain it another way: mathematical

If the input has I inversions, insertion sort makes I shifts and between I and I + n − 1 comparisons. A reversed list of n has n(n − 1)/2 inversions, the maximum.

Explain it another way: applied

Fast general-purpose sorts, including Python's own (Timsort), switch to insertion sort on short runs of data because it is so quick on small or nearly sorted pieces.

Try these examples

Example 1

Insertion sort that counts comparisons, on part masses in grams.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Part masses (g) arrive as a = [32, 59, 17, 37, 44, 26]. They are sorted with insertion sort, where each new key moves left while j >= 0 and a[j] > key. Counting every evaluation of a[j] > key, how many comparisons are made?

Answer: comparisons

2. How many comparisons does insertion sort make on a reversed list of 10 items?

Answer: comparisons

3. Part masses (g) arrive as a = [36, 35, 27, 11, 5]. They are sorted with insertion sort, where each new key moves left while j >= 0 and a[j] > key. Counting every evaluation of a[j] > key, how many comparisons are made?

Answer: comparisons

4. A 1,000-item log is sorted except for two neighbouring entries that are swapped. Roughly how many comparisons does insertion sort make?

  • About 1,000
  • About 500,000
  • About 10,000
  • Exactly 2

5. Two runs both drew 1.5 A; run 4 is listed before run 9. After a stable sort by current, which comes first?

  • Run 4
  • Run 9
  • It is random

Apply it

Generate lists of 100, 200 and 400 random numbers, and nearly sorted lists of the same sizes. Count insertion-sort comparisons for each and put them in a table. Does doubling n roughly quadruple the count for random data? What happens for nearly sorted data?

Reflect

Where in your work does data arrive nearly sorted already? What does that mean for the sort you should choose?

Go further (online)

Sort once, search many: when sorting pays

Sorting 10,000 part numbers costs work up front. After how many lookups has it paid for itself?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Engineering is about total cost, not the cost of one step. Sorting is an investment: you pay once and every later search is cheap. Knowing when that investment pays off, and when a set beats both, is the kind of judgement that separates working code from good code.

Goals

Predict

A list has 1,024 unsorted items. Sorting costs about n·log₂ n ≈ 10,000 comparisons; each later binary search costs about 11. A linear search costs about 512 on average. Roughly how many searches before sorting first is cheaper?

  1. About 2
  2. About 20
  3. About 200
  4. Never

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, generate 5,000 random part numbers and 1,000 lookups. Time three strategies: linear search each time, sorted() then bisect, and a set. Repeat with only 5 lookups. Which strategy wins in each case, and by roughly how much?

What the interactive shows, in words

The Code Lab activity can be done on paper with the cost models: for n = 1024, linear search costs 512 comparisons per lookup; sorting costs about 10,240 once plus 10 per lookup. Linear is cheaper up to 20 lookups; sorting first is cheaper from 21 lookups.

Understand

Total cost is what matters

With n items and k searches, linear search costs about k·n/2 comparisons. Sorting costs about n·log₂ n with a good sort, then each binary search about log₂ n. Write both totals and compare them for your actual n and k.

The break-even point

Set k·n/2 = n·log₂ n + k·log₂ n and solve for k. For large n the break-even is roughly k ≈ 2·log₂ n: only a few dozen searches even for millions of items. If you'll search more than that, sort first.

Or skip ordering entirely

If you only ask 'is it there?' or 'what's its value?', building a set or dict costs about n steps and each lookup about 1. Sorting still wins when you need order: ranges ('all parts between 2000 and 2100'), nearest values, or the top ten.

Explain it another way: intuitive

Tidying your toolbox takes ten minutes. If you need one spanner today, just rummage. If you'll need tools all term, tidy once.

Explain it another way: technical

Costs, in comparisons: linear k·n/2 average; sort + binary n log₂ n + k log₂ n; set build ≈ n hashes, then ≈ 1 per lookup. Real timings also depend on constants: Python's sorted() runs in optimised C, so measured break-evens can differ from the comparison count.

Explain it another way: mathematical

Break-even: k·n/2 = (n + k)·log₂ n gives k = n·log₂ n / (n/2 − log₂ n). For n = 1024: k = 10240 / (512 − 10) ≈ 20.4.

Explain it another way: applied

Databases make exactly this trade-off when they build an index: extra cost on every insert, in exchange for fast lookups and range queries on every read.

Try these examples

Example 1

Compare comparison counts for k lookups on n = 1024 items.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Linear search averages n/2 comparisons. For n = 2,000 items and k = 30 lookups, about how many comparisons in total?

Answer: comparisons

2. You must repeatedly list every part number between 2000 and 2100. Which preparation is best?

  • A set
  • Sort once, then binary-search for 2000 and read forwards
  • Linear search each time
  • A dict of part numbers to quantities

3. A sorted list holds 50 calibration points. Binary search compares the target with one middle element per loop and halves the range each time. In the worst case (including a target that is not there), how many elements does it compare with the target?

Answer: comparisons

4. You need to check ONE part number in an unsorted list of 50,000, once. Best plan?

  • Sort, then binary search
  • Build a set first
  • Linear search
  • Sort twice to be safe

5. Using cost models linear = k·n/2 and sorted = n·log₂n + k·log₂n, with n = 256, what is the smallest whole number of searches k for which sorting first is cheaper?

Answer: searches

Apply it

Write up the Code Lab experiment as a short investigation: question, three strategies, n and k values, a table of measured times (best of five runs), and a conclusion about which strategy you'd use for a stores catalogue that is searched 200 times a day and updated once a week.

Reflect

What was the most surprising difference between the comparison-count prediction and your measured times?

Go further (online)

Week 6: Computational efficiency

This week you will

Count the steps before you time them

Checking every pair of 1,000 waypoints for collisions: is that 1,000 checks, 500,000, or a million?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Before you measure a program you can often predict its cost by counting: how many times does the innermost line run? That count, as a formula in n, tells you whether your planner will cope with a 10× bigger map, before you build the map.

Goals

Predict

count = sum(1 for i in range(n) for j in range(i)) checks each pair of n waypoints once. For n = 1,000, what is count?

  1. 1,000
  2. 499,500
  3. 1,000,000
  4. 2,000

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Turn on only n and n² and slide n from 2 to 1,000. Read the 'when n doubles' column. Then add n log n and log n. Which growth would your collision check (all pairs) follow?

What the interactive shows, in words

The plotter draws operation counts against n for log n, n, n log n and n², and a table gives each count and the factor it grows by when n doubles: about 1 extra step for log n, 2 for n, a little over 2 for n log n and 4 for n².

Understand

Single and nested loops

A loop over range(n) runs n times. A loop inside a loop multiplies: range(a) around range(b) runs a × b times. Three nested loops over n run n³ times. Loops one after another add: n + n = 2n.

When the inner loop depends on the outer

If the inner range uses i, add up the inner counts. range(i) gives 0 + 1 + … + (n − 1) = n(n − 1)/2; range(i, n) gives n + (n − 1) + … + 1 = n(n + 1)/2. A step, range(0, n, k), runs ⌈n/k⌉ times.

Count the expensive line

You don't need to count every statement. Pick the line that runs most often (a comparison, a distance calculation) and count that. Its formula dominates the program's cost as n grows.

Explain it another way: intuitive

Shaking hands with everyone in a room of n people: each new person shakes hands with all who arrived before. That's the triangular count, about half of n².

Explain it another way: technical

Counts are functions T(n). Rules: sequence adds, nesting multiplies, dependent loops sum. Keep exact counts when n is small and you're comparing designs; switch to growth rates (next lesson) for large n.

Explain it another way: mathematical

Σ_{i=0}^{n−1} i = n(n − 1)/2, Σ_{i=0}^{n−1} (n − i) = n(n + 1)/2, Σ_{i=0}^{n−1} 1 = n. Number of values in range(0, n, k) = ⌈n/k⌉.

Explain it another way: applied

A naive collision check of every pair of n moving parts is n(n − 1)/2 distance calculations per frame; that's why simulators divide space into cells and only compare neighbours.

Derivation: Why the triangular loop costs n(n − 1)/2
  1. The loop for i in range(n): for j in range(i): runs the inner body i times on pass i, for i = 0, 1, …, n − 1.

  2. Total S = 0 + 1 + 2 + … + (n − 1).

  3. Write the sum forwards and backwards and add: each column gives (n − 1), and there are n columns, so 2S = n(n − 1).

  4. Therefore S = n(n − 1)/2. For n = 1000: 1000 × 999 / 2 = 499,500.

  5. For large n this is about n²/2: still quadratic. Doubling n multiplies it by about 4.

Try these examples

Example 1

Count the pair checks for n waypoints and confirm with the formula.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A program is comparing every pair of waypoints. Its step count is measured with: count = sum(1 for i in range(0, 266, 10)). What value does count hold?

Answer: steps

2. A program is filling a cost table for a route planner. Its step count is measured with: count = sum(1 for i in range(10) for j in range(6)). What value does count hold?

Answer: steps

3. A program is scanning a sensor log. Its step count is measured with: count = sum(1 for i in range(36) for j in range(i)). What value does count hold?

Answer: steps

4. pair_checks(1000) is 499,500. About how big is pair_checks(2000)?

  • About 1 million
  • About 2 million
  • About 4 million
  • About 999,000

5. One loop over n readings filters spikes; a second loop over n readings averages them. How many loop passes in total?

  • n
  • 2n
  • n²
  • n(n − 1)/2

Apply it

For your BFS planner, count how many times the neighbour check runs on an open n × n grid (each cell is expanded once and checks 4 neighbours). Write the formula, then check it by adding a counter to your code for n = 10, 20 and 40.

Reflect

Which loop in your own recent code runs most often, and what is its count as a formula?

Big-O: the shape of growth

Algorithm A takes 3n² + 50n + 1000 steps; algorithm B takes 400n. Which would you choose for a map with a million cells?

About 40 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Big-O is the engineer's shorthand for 'how does the cost grow?'. It ignores details that don't matter for large inputs, so you can compare designs on paper and spot the one that will collapse when the map, the log or the parts list gets ten times bigger.

Goals

Predict

A = 3n² + 50n + 1000 steps, B = 400n steps. For n = 1,000,000, roughly how many times more steps does A take?

  1. About the same
  2. About 10 times
  3. About 7,500 times
  4. About a million times

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Switch on the logarithmic y-axis so all four curves fit. Then raise the constant in front of n log n to 20 and find where n² overtakes it. What does that tell you about small inputs versus large ones?

What the interactive shows, in words

The plotter shows log n, n, n log n and n² against n, optionally on a logarithmic y-axis. A slider multiplies n log n by a constant; with a constant of 20, n² is cheaper until about n = 145, after which n² grows far faster.

Understand

Keep the top term, drop the constant

From an exact count, keep the term that grows fastest and drop its coefficient: 5n + 20 → O(n); n(n − 1)/2 → O(n²); 4 log₂ n + 7 → O(log n). Big-O describes the shape of growth, not the exact number of steps.

The usual ladder

O(1) constant (dict lookup) < O(log n) (binary search) < O(n) (one scan) < O(n log n) (good sorts) < O(n²) (all pairs, insertion sort) < O(n³) (three nested loops). Doubling n adds a step, doubles, slightly more than doubles, quadruples, and multiplies by 8.

Predicting from a measurement

If you measure 20 ms at n = 1,000 and the code is O(n²), expect about 20 × 4 = 80 ms at n = 2,000 and 20 × 100 = 2 s at n = 10,000. Then test the prediction: if the measurement disagrees, your model of the code is wrong somewhere.

Explain it another way: intuitive

Big-O is like describing a hill by its steepness rather than its exact height: a steep hill always ends up higher eventually, however far back it starts.

Explain it another way: technical

f(n) is O(g(n)) if there are constants c and n₀ with f(n) ≤ c·g(n) for all n ≥ n₀. Usually we quote the worst case; average and best cases can differ (insertion sort: best O(n), worst O(n²)).

Explain it another way: mathematical

Ratios on doubling: (2n)²/n² = 4; (2n)³/n³ = 8; (2n log 2n)/(n log n) = 2(1 + 1/log₂ n); log₂(2n) − log₂ n = 1.

Explain it another way: applied

Choosing an O(n log n) planner step over an O(n²) one is often the difference between a robot that replans in real time on a big warehouse map and one that freezes.

Derivation: Why constants and smaller terms are dropped
  1. Take T(n) = 3n² + 50n + 1000. Divide by n²: T(n)/n² = 3 + 50/n + 1000/n².

  2. As n grows, 50/n and 1000/n² shrink towards 0, so T(n)/n² approaches 3. The n² term ends up doing almost all the work.

  3. Big-O asks only how T grows, up to a constant factor: T(n) ≤ c·n² for some constant c once n is large enough (here c = 4 works for n ≥ 66). So T(n) is O(n²).

  4. The constant 3 is dropped because it depends on the machine and the language; the exponent 2 doesn't. Doubling n multiplies any O(n²) cost by about 4, whatever the constant.

Try these examples

Example 1

Predict from a measurement for three growth rates.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. An exact count is T(n) = 7n + 3n·log₂n + 12. What is its big-O?

  • O(n)
  • O(n log n)
  • O(7n)
  • O(12)

2. Timing tests show a collision checker grows like n and takes 5 ms for n = 4096. Assuming that growth holds, predict its time for n = 8192, in ms.

Answer: ms

3. Timing tests show a parts-matching script grows like n² and takes 12 ms for n = 1024. Assuming that growth holds, predict its time for n = 4096, in ms.

Answer: ms

4. Which list is in order from slowest-growing to fastest-growing?

  • n, log n, n², n log n
  • log n, n, n log n, n²
  • n², n log n, n, log n
  • 1, n², n, log n

5. Algorithm X is O(n log n) and Y is O(n²). Which statement is true?

  • X is always faster than Y
  • X will be faster for large enough n, but Y may be faster for small n
  • They are equally fast
  • Y is always faster

Apply it

Write the big-O of each function in your planner package (loading, neighbours, BFS, report). Pick the one with the worst growth and predict how its time changes when the map grows from 50 × 50 to 200 × 200. Keep the prediction for the next lesson's measurements.

Reflect

In one sentence each: what does big-O tell you, and what doesn't it tell you?

Module check: measure growth, then explain it

Your model says the planner is O(n). The stopwatch says doubling the map quadruples the time. Who's right?

About 45 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Big-O is a prediction; timings are evidence. Good engineers measure to check the prediction, and when they disagree, they find out why. This module check brings weeks 4–6 together in one honest experiment.

Goals

Predict

You time a function at n = 1,000 (12 ms), 2,000 (47 ms) and 4,000 (190 ms). What growth does this suggest?

  1. O(n)
  2. O(n log n)
  3. O(n²)
  4. O(log n)

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, time your visited-as-list BFS and your visited-as-set BFS on open grids of 20 × 20, 40 × 40, 80 × 80 (and 160 × 160 if it's quick). Use the best of five runs. Each step doubles the side, so the number of cells quadruples. What time ratio does each version show per step, and what growth does that suggest?

What the interactive shows, in words

The Code Lab experiment can be done from a table: list-based visited checks grow roughly 4 times when the number of cells doubles (quadratic), while set-based visited checks grow roughly 2 times (linear). The worked example's duplicate counter shows the same pattern, with an estimated exponent near 2 for the list and near 1 for the set.

Understand

Fair timing

Use time.perf_counter() or timeit; run each size several times and report the best or the median (the first run is often slow while Python warms up). Change only n. Close other heavy programs. Record the machine and Python version so others can compare.

Read growth from ratios

When the input doubles, the time ratio tells you the growth: about 2 for O(n), a bit over 2 for O(n log n), about 4 for O(n²). Plotting time against n on log–log axes turns a power law into a straight line whose slope is the exponent.

What big-O won't tell you

Constants (C code inside Python is far faster than Python loops), memory and caching effects, small-input overheads and noise from other programs. A careful report states the prediction, the measurement and an explanation of any gap.

Explain it another way: intuitive

Weighing yourself once on a wobbly floor tells you little. Weigh several times, on a firm floor, and look at the trend over weeks.

Explain it another way: technical

If T(n) ≈ c·n^p, then log T = log c + p·log n, so p ≈ log(T₂/T₁)/log(n₂/n₁). With doubling, p ≈ log₂(T₂/T₁). Noise of a few per cent is normal; use several sizes, not two.

Explain it another way: mathematical

From 12, 47 and 190 ms: p ≈ log₂(47/12) ≈ 1.97 and log₂(190/47) ≈ 2.02, so p ≈ 2.

Explain it another way: applied

Performance regressions in large codebases are usually caught by benchmarks that run at several input sizes and alert when the growth exponent changes, not just when one time gets slower.

Try these examples

Example 1

Time a list-membership check versus a set at several sizes and estimate the exponent.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Times: 30 ms at n = 5,000 and 240 ms at n = 10,000. Estimate the exponent p in T ≈ c·n^p.

Answer:

2. Which timing method is most trustworthy?

  • Run once and report the time
  • Run five times per size, report the best (or median), change only n
  • Time each size on a different computer
  • Time while also downloading a large file

3. Timing tests show a parts-matching script grows like n² and takes 12 ms for n = 1024. Assuming that growth holds, predict its time for n = 4096, in ms.

Answer: ms

4. A program is scanning a sensor log. Its step count is measured with: count = sum(1 for i in range(46) for j in range(i, 46)). What value does count hold?

Answer: steps

5. Big-O predicts O(n), but doubling n multiplies your measured time by 4. What is the best next step?

  • Trust big-O and ignore the timings
  • Look for a hidden inner loop, such as 'x in some_list' inside the main loop
  • Buy a faster computer
  • Report O(n) anyway

6. Which of these does big-O NOT tell you?

  • How the cost grows as n grows
  • How long the code takes in seconds on your laptop at n = 100
  • Which of two algorithms wins for very large n (if their big-O differ)
  • That doubling n roughly quadruples an O(n²) cost

Apply it

Module check deliverable. A one-page investigation: your BFS with visited as a list and as a set, timed on at least four grid sizes (best of five). Include a table, an estimated exponent for each version, your big-O prediction for each, and a paragraph explaining any disagreement. State your machine and Python version.

Reflect

What did measuring teach you that counting alone did not?

Go further (online)

Week 7: Numerical computation

This week you will

Bisection: trap the answer, halve the trap

No formula gives the cable tension where a sag equation balances. But if you know one guess is too low and one too high, you can corner the answer to any accuracy you like.

About 40 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Many engineering equations have no neat algebraic solution: a cam profile meeting a follower, a cable's catenary, a motor's operating point. Numerical methods solve them by iteration: improve a guess again and again until the error is small enough. Bisection is the slow, unbreakable one.

Goals

Predict

Bisection starts with the bracket [0, 2]. How wide is the bracket after 10 steps?

  1. 0.2
  2. About 0.002
  3. About 0.0000002
  4. It depends on the equation

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Choose x² − 2 and Bisection. Step ten times and watch the lavender bracket and the error column. Then move the ends so f(a) and f(b) have the same sign. Finally try cos x − x: does the bracket still halve at the same rate?

What the interactive shows, in words

The stepper plots f(x) = x² − 2 on 0 to 3 with a lavender bracket. Each bisection step halves the bracket: [0, 2], [1, 2], [1, 1.5], [1.25, 1.5] and so on, closing in on 1.41421. With ends that give f the same sign, the stepper reports that bisection cannot start.

Understand

Bracket, test, keep half

Pick a and b with f(a) * f(b) < 0. Compute the midpoint m. If f(m) has the same sign as f(a), the root is in [m, b]; otherwise it is in [a, m]. Repeat until the bracket is narrower than your tolerance.

Error you can predict

The error after k steps is at most (b − a)/2^(k+1) if you report the midpoint. That bound does not depend on the equation at all, so you can plan the computation before you run it. Each step gains one binary digit of accuracy (linear convergence).

When it fails

Bisection needs a sign change. A root where the curve only touches zero (like x² at 0) has no sign change and can't be bracketed. A discontinuity (like 1/x) can fake a sign change with no root. Always check f(a)·f(b) < 0 first and plot f if unsure.

Explain it another way: intuitive

Guessing someone's age with 'older or younger?': each answer halves the range. You can't miss, and you know how many questions you'll need.

Explain it another way: technical

Stop on a bracket-width tolerance, not on f(m) == 0 (exact zeros are rare in floating point). Also cap the number of iterations. Python's standard library has no bisection root finder, but the loop is only a few lines.

Explain it another way: mathematical

Convergence is linear with rate 1/2: e_{k+1} ≈ e_k/2. To gain d decimal digits you need about d·log₂ 10 ≈ 3.32·d steps.

Explain it another way: applied

Bisection is often used as a safe fallback inside faster solvers: if a quick method misbehaves, the solver falls back to halving a bracket it trusts.

Derivation: How many bisection steps for a given accuracy?
  1. Start with a bracket [a, b] where f(a) and f(b) have opposite signs, so a continuous f must cross zero somewhere inside (the intermediate value theorem).

  2. Each step tests the midpoint m = (a + b)/2 and keeps the half where the sign still changes. The new bracket has width (b − a)/2.

  3. After k steps the width is w_k = (b − a)/2^k. The root is always inside, so the midpoint is within w_k/2 of it.

  4. To guarantee w_k ≤ tol we need 2^k ≥ (b − a)/tol, so k = ⌈log₂((b − a)/tol)⌉.

  5. Example: [0, 2] to a width of 10⁻⁶ needs ⌈log₂(2 × 10⁶)⌉ = ⌈20.93⌉ = 21 steps. Each extra decimal place costs about 3.3 more steps.

Try these examples

Example 1

Find √2 as the root of x² − 2 on [0, 2] to a width of 10⁻⁶.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A cable tension must satisfy f(x) = x**2 - 11 = 0. Bisection starts on [1, 4] (f(1) < 0 < f(4)), tests the midpoint each step and keeps the half where the sign changes. What midpoint is tested in step 2? Give 4 decimal places.

Answer:

2. Bisection starts from the bracket [0, 2] and stops once the bracket width is at most 0.05. What is the smallest number of steps that guarantees this?

Answer: steps

3. Bisection starts from the bracket [1, 3] and stops once the bracket width is at most 0.001. What is the smallest number of steps that guarantees this?

Answer: steps

4. A cable tension must satisfy f(x) = x**2 - 7 = 0. Bisection starts on [1, 4] (f(1) < 0 < f(4)), tests the midpoint each step and keeps the half where the sign changes. What midpoint is tested in step 4? Give 4 decimal places.

Answer:

5. f(x) = (x − 1)² on [0, 3]. Why can't bisection start?

  • The root is outside the bracket
  • f(0) and f(3) are both positive, so there is no sign change to trap
  • Squares can't be computed numerically
  • The bracket is too wide

Apply it

A cam follower's height is h(θ) = 0.02·cos θ + 0.005·θ (metres, θ in radians). Use bisection to find the angle in [0, 2] where h = 0.01 m, to a width of 10⁻⁵. Predict the number of steps first, then check your code matches.

Reflect

Bisection is slow but certain. Name a situation in engineering where certainty is worth the extra steps.

Newton's method: ride the tangent

Bisection needs about 20 steps for six decimal places. Newton's method often needs four. What's the catch?

About 40 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Newton's method uses the slope of the function to jump straight towards the root. Near a well-behaved root it roughly doubles the number of correct digits every step, which is why calculators and microcontrollers use it for square roots. But it trusts the tangent, and tangents can lie.

Goals

Predict

Newton's method on x² − 2 from x₀ = 1 gives x₁ = 1.5, then x₂ ≈ 1.41667. Roughly how many correct decimal places will x₃ have?

  1. About 2
  2. About 5
  3. About 12

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Choose x² − 2 and Newton. Step four times and compare the error column with bisection's. Then choose arctan x (Newton trap): start at 1.0, then at 1.5. What does the tangent do from 1.5?

What the interactive shows, in words

The stepper shows Newton's method on x² − 2 from 1: the orange tangent at each guess meets the axis at the next guess, 1.5, 1.41667, 1.4142157, with the error column shrinking from 10⁻¹ to 10⁻³ to 10⁻⁶ to 10⁻¹². For arctan x from 1.5, each tangent lands further away and the readout reports divergence.

Understand

Fast when close

From a good starting guess, Newton's method converges quadratically: the number of correct digits roughly doubles each step. For x² − 2 from 1, four steps give about 12 correct digits, where bisection on [0, 2] would need about 40.

It needs the derivative

You must supply f′(x), worked out by hand or estimated numerically. If f′(x_k) = 0 the tangent is flat and never crosses zero: the method can't continue. Guard against it and cap the number of steps.

It can run away

If the start is far from the root, or the function flattens out, the tangent can throw the next guess further away. arctan x from x₀ = 1.5 diverges. Engineers often bracket first with bisection, then switch to Newton once close, or reject any Newton step that leaves the bracket.

Explain it another way: intuitive

You're on a hillside in fog and want to reach sea level. Look at the slope under your feet and walk straight downhill as if the slope never changed. Near the coast that works brilliantly; on a long flat plateau it can send you miles the wrong way.

Explain it another way: technical

Stop when |x_{k+1} − x_k| < tol or |f(x)| < tol, and after a maximum number of steps. A secant method replaces f′ with the slope through the last two points: slightly slower but needs no derivative.

Explain it another way: mathematical

For f(x) = arctan x, x_{k+1} = x_k − (1 + x_k²)·arctan x_k. If |x₀| exceeds about 1.39, each step overshoots further, so |x_k| grows without bound.

Explain it another way: applied

The fast inverse square root used in some graphics and embedded code finishes with one Newton step, because a single step from a rough guess already gives close to full accuracy.

Derivation: Where the Newton update comes from
  1. Near a guess x_k, replace the curve by its tangent line: y ≈ f(x_k) + f′(x_k)·(x − x_k).

  2. Find where that line crosses zero: 0 = f(x_k) + f′(x_k)·(x − x_k).

  3. Solve for x: x_{k+1} = x_k − f(x_k)/f′(x_k). This needs f′(x_k) ≠ 0.

  4. For f(x) = x² − c, f′(x) = 2x, so x_{k+1} = x_k − (x_k² − c)/(2x_k) = (x_k + c/x_k)/2: average the guess with c divided by the guess.

  5. Near a simple root the error obeys e_{k+1} ≈ C·e_k², so an error of 10⁻³ becomes about 10⁻⁶, then 10⁻¹². That's quadratic convergence.

Try these examples

Example 1

Newton's method with a step limit and a flat-slope guard, compared with the true root.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A microcontroller finds a vector length L = √12 with Newton's method on f(x) = x**2 - 12, using x = x - (x**2 - 12) / (2*x). Starting from x0 = 1, what is x after 2 iterations? Give 4 decimal places.

Answer:

2. A microcontroller finds a vector length L = √3 with Newton's method on f(x) = x**2 - 3, using x = x - (x**2 - 3) / (2*x). Starting from x0 = 5, what is x after 1 iteration? Give 4 decimal places.

Answer:

3. Newton's method on f(x) = x² − 4 starts at x₀ = 0. What happens?

  • It converges to 2
  • It converges to −2
  • It fails: f′(0) = 0, so the update divides by zero
  • It converges slowly

4. Which statement compares bisection and Newton fairly?

  • Newton is always better
  • Bisection is guaranteed given a sign change but slow; Newton is much faster near a root but can fail from a poor start
  • Bisection needs the derivative
  • They converge at the same rate

5. Newton's method on f(x) = x³ − 2x − 5 from x₀ = 2. What is x₁ (4 decimal places)?

Answer:

Apply it

Write a hybrid solver: keep a bisection bracket, try a Newton step each iteration, and fall back to bisection whenever Newton would leave the bracket. Test it on x³ − 2x − 5 on [2, 3] and on arctan x on [−1, 2], and count steps compared with pure bisection.

Reflect

Why might a safety-critical system prefer a slower method with a guarantee?

Speed from position, distance from speed: calculus on samples

Your encoder gives position every 10 ms. Differentiate to get speed and the plot turns into hair. Integrate speed to get distance and it's beautifully smooth. Why the difference?

About 40 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Robots measure in samples, not formulas. Speed comes from differencing positions; distance and energy come from summing speeds and powers. Knowing how each operation treats noise tells you which results to trust and when to filter first.

Goals

Predict

Positions are logged every 0.01 s and each reading has up to ±0.5 mm of noise. A forward-difference speed estimate could be wrong by up to about…

  1. ±0.5 mm/s
  2. ±1 mm/s
  3. ±100 mm/s
  4. ±0.01 mm/s

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, make clean positions x = 0.2·t² for t from 0 to 2 s every 0.01 s, then add random noise of ±0.5 mm. Compute speed with forward differences, and distance from the true speed with the trapezium rule. Compare both with the exact answers. Then try h = 0.05 s.

What the interactive shows, in words

The Code Lab activity can be done on paper: for x = 0.2t² sampled every 0.01 s, the forward difference at t = 1 s gives 0.402 m/s, the central difference 0.400 m/s, and with ±0.5 mm noise the forward difference can be off by up to 0.1 m/s. The trapezium rule on the speed samples gives the exact distance 0.8 m.

Understand

Derivatives from differences

Forward difference: (x[i+1] - x[i]) / h, an estimate of the speed between two samples. Central difference: (x[i+1] - x[i-1]) / (2 * h), centred on sample i and usually more accurate for smooth data (its error shrinks like h² rather than h).

Integrals from trapezia

Join neighbouring samples with straight lines and add the areas: h * (v[0]/2 + v[1] + ... + v[-2] + v[-1]/2). For speed samples this gives distance; for power samples, energy. Its error shrinks like h² for smooth data.

Noise changes the advice

On clean data, smaller h is always better. On noisy data, differencing divides the noise by h, so too-small steps make speed estimates useless. Integrate when you can, smooth before you differentiate, and always state the sample interval in your report.

Explain it another way: intuitive

Speed is about how much something changed between two looks. If each look is a bit shaky, comparing two looks very close together mostly measures the shake.

Explain it another way: technical

Truncation error: forward O(h), central O(h²), trapezium O(h²). Noise error: differences O(ε/h); trapezium total about ε·h·√N for N random readings. The best h for a derivative balances the two.

Explain it another way: mathematical

For x = 0.2t², the exact speed is 0.4t. A forward difference gives 0.4t + 0.2h: exactly linear in h. A central difference gives 0.4t with no truncation error for a quadratic.

Explain it another way: applied

Motor controllers often estimate speed by counting encoder ticks over a longer window rather than differencing every sample, trading a little delay for much less noise.

Derivation: Why differences amplify noise
  1. Each reading is x_i + n_i, where the noise n_i is at most ε in size.

  2. Forward difference: ((x_{i+1} + n_{i+1}) − (x_i + n_i))/h = (x_{i+1} − x_i)/h + (n_{i+1} − n_i)/h.

  3. The noise term can be as large as 2ε/h. Halving h doubles it.

  4. The trapezium rule multiplies each reading by h and adds them, so noise enters as h·Σn_i. Random noise partly cancels in the sum: integration smooths, differentiation sharpens.

  5. So choose h large enough that 2ε/h is acceptable, or smooth the readings first (for example with a moving average), or use a central difference over 2h.

Try these examples

Example 1

Differentiate and integrate clean and noisy samples of x = 0.2t² (metres).

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A linear-axis encoder logs position every 0.1 s: x = [11, 20, 29, 32, 38, 45] mm. Estimate the speed at sample index 4 using a forward difference (x[i+1] - x[i]) / h, in mm/s.

Answer: mm/s

2. A rover logs wheel speed every 2 s: v = [1, 1, 5, 5.5] m/s. Using the trapezium rule, how far did it travel between the first and last sample, in metres?

Answer: m

3. A rover logs wheel speed every 1 s: v = [3.5, 3.5, 2.5, 1, 0] m/s. Using the trapezium rule, how far did it travel between the first and last sample, in metres?

Answer: m

4. A linear-axis encoder logs position every 0.5 s: x = [15, 24, 29, 35, 40, 41] mm. Estimate the speed at sample index 3 using a central difference (x[i+1] - x[i-1]) / (2*h), in mm/s.

Answer: mm/s

5. Readings have noise up to ±0.2 mm and are 0.004 s apart. What is the largest possible noise in a forward-difference speed, in mm/s?

Answer: mm/s

6. Speed from a noisy encoder is too jumpy. Which change helps most without new hardware?

  • Sample faster and difference neighbouring samples
  • Difference over a longer interval, or smooth positions first
  • Round positions to whole millimetres
  • Integrate the speed again

Apply it

From the Code Lab experiment, make a table of the maximum speed error against h (0.005, 0.01, 0.02, 0.05, 0.1 s) for noisy data. Find the h with the smallest error and explain the trade-off you see between noise and truncation error.

Reflect

When you next see a jagged speed plot from a robot, what two questions will you ask about how it was computed?

Week 8: Data visualisation

This week you will

Choose the plot that answers the question

Same sensor log, three questions: is it drifting? How noisy is it? Is it related to temperature? Why should those be three different charts?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

A chart is an answer to a question. Pick the wrong kind and the answer is hidden, however good the data. Engineers choose the plot after writing the question down, and label it so a reader can check it without asking them.

Goals

Predict

You want to see how a motor's temperature changed during a 30-minute test. Which plot?

  1. A pie chart of temperatures
  2. A line plot of temperature against time
  3. A histogram of temperatures
  4. A bar chart of the average

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Switch between bars and a line. Which form makes the change over the year easiest to read? Which makes the before/after comparison easiest? Then turn on the error bars: what extra question can you now answer?

What the interactive shows, in words

The chart critique shows monthly conveyor jams as bars or as a line. A line shows the change across the year most clearly; bars from zero make the before and after levels easy to compare; error bars show the day-to-day spread so the size of the change can be judged against it.

Understand

Question first, plot second

Change over time → line (time on x). Relationship between two measurements → scatter. Spread of one measurement → histogram (or box plot). Comparing a few groups → bars (from zero) or points with error bars. Parts of a whole → a stacked bar is usually clearer than a pie.

Label like a datasheet

Every axis gets a quantity and a unit: 'Motor temperature (°C)', 'Time (s)'. Add a title that states the finding or the question, a legend if there is more than one series, and a note of where the data came from and how many samples.

Show the data, not just a summary

Plot the individual readings when you can, and add the mean on top. A single average bar hides spread, outliers and drift, which are often exactly what an engineer needs to see.

Explain it another way: intuitive

A map answers 'where?', a clock answers 'when?'. Charts are the same: each kind answers a different kind of question well.

Explain it another way: technical

In matplotlib, fig, ax = plt.subplots() then ax.plot(x, y) for lines, ax.scatter for relationships, ax.hist for distributions and ax.bar for comparisons; ax.set_xlabel, ax.set_ylabel and ax.set_title label it; fig.savefig("plot.png", dpi=150) saves it.

Explain it another way: applied

Engineering test reports usually standardise their charts: time series with units on both axes, the same colours for the same sensor in every figure, and the number of samples in each caption.

Try these examples

Example 1

A fully labelled line plot of a motor temperature log.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Does a servo's current draw rise with the load on its arm? You have 40 (load, current) pairs. Which plot?

  • Line plot of current in the order measured
  • Scatter plot of current against load
  • Pie chart of currents
  • Histogram of loads

2. How noisy is a gyro at rest? You have 5,000 readings. Which plot shows the spread best?

  • A histogram of the readings
  • A bar chart of the mean
  • A pie chart
  • A single number: the maximum

3. Which y-axis label is best?

  • 'Temp'
  • 'Data'
  • 'Motor case temperature (°C)'
  • 'y'

4. A log of motor temperature (°C) reads xs = [63, 66, 59, 62, 60, 54, 60]. What is the median, statistics.median(xs)? Give 2 decimal places.

Answer:

Apply it

Take a sensor log you have (or the motor test CSV from week 3). Write three questions about it and make one correctly chosen, fully labelled plot for each. Under each, write one sentence answering its question.

Reflect

Which plot type do you overuse, and which question does it fail to answer?

Charts that lie without a single false number

A chart shows jams falling by two-thirds after a fix. The data shows 6%. Nobody changed a number. What did they change?

About 40 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Engineers make decisions from charts: which supplier, which design, whether a fix worked. A chart can mislead through choices alone. Learning to spot those choices protects you from other people's charts, and your reports from your own wishful thinking.

Goals

Predict

A bar chart's y-axis runs from 36 to 48. Bars show 41.5 and 39. How many times taller does the first bar look than it 'should'?

  1. About the same
  2. The difference looks about 13 times bigger than it is
  3. Exactly twice

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Start with the chart as it opens and read the lie factor. Fix one problem at a time: start the axis at zero, show the whole year, add the error bars. After each fix, what does the chart now say about whether the new belt guide worked?

What the interactive shows, in words

The critique opens with jams for May to September on an axis from 36: before about 41.5, after about 39, which looks like an 83% drop (lie factor about 13). Starting the axis at zero brings the lie factor to 1; showing all twelve months gives 41.8 before and 39.2 after (about 6.8%); error bars of ±4.2 show the change is within day-to-day spread.

Understand

Truncated axes

Bar length encodes the value, so a bar axis that doesn't start at zero exaggerates differences. Line charts can zoom to show small changes, but the axis numbers must be visible and the caption should say so.

Cherry-picked windows

Showing only the months that support a story hides what happened around them. Show the whole record, or explain why a window was chosen before looking at the results. Mark when an intervention happened.

Change versus spread

A 2.5-jam drop means little if daily counts vary by ±4. Error bars, raw points or a histogram of the noise let readers compare the change with the natural variation. 'Promising but not yet convincing' is an honest and useful conclusion.

Explain it another way: intuitive

A photo can make a puddle look like a lake by zooming in and cropping out the edges. Charts can do the same with axes and ranges.

Explain it another way: technical

Common distortions: non-zero bar baselines, dual y-axes with arbitrary scaling, area or 3D effects that scale values quadratically, uneven time intervals, and smoothing that hides outliers. Each changes the visual effect without changing the data.

Explain it another way: mathematical

Lie factor = (visual relative change)/(data relative change). For a baseline b and values y₁ > y₂: L = y₂/(y₂ − b). As b approaches y₂ the lie factor grows without bound.

Explain it another way: applied

Many engineering organisations require full axes, units and uncertainty on charts in design reviews, because a single exaggerated chart can push a team into an expensive wrong decision.

Derivation: The lie factor
  1. Effect in the data: the relative change (before − after)/after. For 41.5 → 39: 2.5/39 ≈ 0.064 (6.4%).

  2. Effect in the graphic: bars are drawn from the axis baseline b, so the relative change in bar height is ((before − b) − (after − b))/(after − b) = (before − after)/(after − b).

  3. With b = 36: 2.5/3 ≈ 0.83 (83%).

  4. Lie factor = graphic effect ÷ data effect = (after)/(after − b) = 39/3 = 13.

  5. With b = 0 the lie factor is exactly 1. That is why bar charts start at zero; line charts may zoom in, as long as the axis is clearly labelled and the zoom is the point.

Try these examples

Example 1

Compute the lie factor for three baselines.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. Bars show 50 and 40 on an axis starting at 30. What is the lie factor? (Data change = (50 − 40)/40; visual change = (50 − 40)/(40 − 30).)

Answer:

2. A chart of battery life shows only months 4–6 of a 12-month trial, the months with the best results. What is the problem?

  • Truncated axis
  • Cherry-picked range
  • Missing units
  • Wrong chart type

3. When is a y-axis that doesn't start at zero acceptable?

  • Never
  • On a line chart where small changes matter, with clearly labelled axis values
  • On any bar chart
  • Whenever it makes the result look better

4. Before/after means are 41.8 and 39.2 jams a day, with day-to-day spread of ±4.2. Which caption is honest?

  • 'Fix eliminates jams'
  • 'Jams fell about 6% after the fix, a change smaller than the day-to-day spread; more data needed'
  • 'No change'
  • 'Jams fell dramatically'

5. A log of motor temperature (°C) reads xs = [42, 50, 49, 47, 47, 44, 43, 44, 47]. What is the mean, statistics.mean(xs)? Give 2 decimal places.

Answer:

Apply it

Find (or make) a misleading chart of engineering data. Redraw it honestly in Python, compute the original's lie factor, and write a two-sentence caption for the honest version that states the change and its uncertainty.

Reflect

Have you ever been convinced by a chart you now think was misleading? What gave it away?

Mean, median and spread: summarising a log honestly

A range sensor logs 9 readings near 48 cm and one glitch at 400 cm. Which single number should go in the report?

About 35 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Before you plot a log you usually summarise it. The mean, median and standard deviation each tell you something different, and one glitch can wreck the wrong choice. An honest summary gives a centre, a spread and n, and says how outliers were handled.

Goals

Predict

Readings: nine values near 48 cm and one glitch of 400 cm. Which summary is barely affected by the glitch?

  1. The mean
  2. The median
  3. The standard deviation
  4. The maximum

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, compute statistics.mean, statistics.median and statistics.stdev for the worked example's readings, with and without the 400 cm glitch. Then replace the glitch with 49 and recompute. Which summary changed most each time?

What the interactive shows, in words

The Code Lab activity can be done from the worked numbers: nine clean readings have mean 48.09 cm, median 48.1 cm and sample standard deviation 0.29 cm. Adding a 400 cm glitch makes the mean 83.28 cm and the standard deviation 111.28 cm, while the median only moves to 48.15 cm.

Understand

Centre: mean or median?

The mean uses every value, so it is sensitive to outliers. The median is the middle value of the sorted data (or the average of the two middle values), so it resists spikes. When they differ a lot, look at the data: something is skewing it.

Spread: standard deviation

The standard deviation is a typical distance of readings from the mean. Roughly two-thirds of normally distributed readings lie within one standard deviation of the mean. Report it with the mean, and say whether it is the sample (n − 1) or population (n) version.

Outliers: decide, then disclose

Never silently delete inconvenient readings. Decide a rule before looking at the results (for example, reject readings outside the sensor's physical range), apply it, and report how many were removed and why.

Explain it another way: intuitive

If one billionaire walks into a café, the mean wealth of the customers rockets; the median barely moves. Sensor glitches are the billionaires of your log.

Explain it another way: technical

statistics.mean, statistics.median and statistics.stdev (sample) or statistics.pstdev (population). The median needs a sort, so it is O(n log n) with a simple implementation; mean and standard deviation are O(n).

Explain it another way: mathematical

For [2, 4, 4, 4, 5, 5, 7, 9]: mean 5, deviations sum of squares 32, sample variance 32/7, s ≈ 2.138; population σ = 2.

Explain it another way: applied

Robot sensor pipelines often use a median filter over the last few readings to reject single-sample spikes before averaging, exactly because the median ignores isolated outliers.

Derivation: Sample standard deviation, step by step
  1. Mean: x̄ = (x₁ + x₂ + … + xₙ)/n.

  2. Deviations: dᵢ = xᵢ − x̄. They always add up to zero, so we square them to measure their size.

  3. Sum of squares: S = Σ dᵢ².

  4. Sample variance: s² = S/(n − 1). Dividing by n − 1 rather than n corrects for using x̄, which is itself estimated from the same data and sits closer to the readings than the true mean does.

  5. Sample standard deviation: s = √(S/(n − 1)), in the same units as the readings. Python's statistics.stdev computes exactly this; statistics.pstdev divides by n.

Try these examples

Example 1

Summarise a range log with and without a glitch.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A log of battery current (A) reads xs = [20, 26, 26, 17, 21, 23, 19, 26]. What is the median, statistics.median(xs)? Give 2 decimal places.

Answer:

2. A log of motor temperature (°C) reads xs = [68, 68, 76, 77, 66]. What is the sample standard deviation, statistics.stdev(xs)? Give 2 decimal places.

Answer:

3. A log of ultrasonic range (cm) reads xs = [49, 49, 47, 44, 42, 51]. What is the sample standard deviation, statistics.stdev(xs)? Give 2 decimal places.

Answer:

4. Which report line is most honest and useful?

  • 'Distance: 48 cm'
  • 'Distance: median 48.1 cm, sample s.d. 0.29 cm, n = 9 (1 reading outside the 2–300 cm rated range removed)'
  • 'Distance: mean 83.3 cm'
  • 'Distance: between 47.6 and 400 cm'

5. Why does statistics.stdev divide by n − 1?

  • To make the number bigger for safety
  • Because deviations are measured from the sample mean, which sits closer to the data than the true mean; n − 1 corrects that underestimate
  • It's a rounding convention
  • Because the first reading doesn't count

Apply it

Write summarise(readings, low, high) that applies a rated-range rule, then returns n kept, n removed, mean, median and sample standard deviation. Test it on a list with no outliers, one with two glitches and an empty list (which should raise a clear error).

Reflect

When would you report the median instead of the mean in your own projects?

Go further (online)

Week 9: Computational engineering project

This week you will

Project: plan a path that counts the cost

BFS finds the fewest moves, straight through the mud. Your rover's battery would rather go round. How does the planner learn to care?

About 50 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

This is the term project: 'plan a path, measure the cost'. You'll combine everything from this term: modules, a map class, a queue and a priority queue, dictionaries, tests and complexity. First, the planner itself.

Goals

Predict

A straight route crosses 3 rough cells (cost 9 each) then 1 floor cell; a detour has 6 floor cells (cost 1 each). Which does Dijkstra choose?

  1. The straight route: fewer moves
  2. The detour: total cost 6 instead of 28
  3. Whichever it finds first

Write down your guess and your reason. The reveal is in the online lesson.

Discover

Run BFS, then Dijkstra, on the default map: compare moves, cost and cells expanded. Then paint a strip of rough ground across the direct route and run both again. Can you build a map where Dijkstra takes twice as many moves as BFS but costs less?

What the interactive shows, in words

The planner shows the same map under BFS and Dijkstra. BFS finds the fewest moves and may cross the rough (cost 5) patch; Dijkstra finds the lowest total cost and may detour round it, expanding cells in order of cost so far. The readout reports moves, total cost and cells expanded for each.

Understand

From queue to priority queue

BFS takes the oldest cell; Dijkstra takes the cheapest-so-far cell. Python's heapq keeps a list as a priority queue: heappush(pq, (cost, cell)) and heappop(pq) returns the smallest cost in O(log n). When a cell is popped, its cost is final.

Relax the neighbours

For each neighbour, the candidate cost is cost[cell] + step_cost(neighbour). If that beats the best known cost, record it, set came_from, and push it. Old, worse entries may stay in the heap; skip them when popped if the cell is already finished.

Project structure

grid.py (a GridMap class with neighbours and cost), planners.py (bfs and dijkstra as functions taking a map), experiment.py (timing and counting), test_planners.py (corridor, detour, unreachable goal, uniform-cost map where both agree). Each planner returns the path, its cost and the number of cells expanded.

Explain it another way: intuitive

Dijkstra is like water flowing through ground of varying difficulty: it always advances where progress is cheapest, so the first time it reaches the goal it has found the cheapest way there.

Explain it another way: technical

With a binary heap, Dijkstra runs in O((V + E) log V). On a grid E ≈ 4V, so O(V log V). It needs non-negative costs. On a uniform-cost grid it expands cells in the same order of distance as BFS but pays a log factor for the heap.

Explain it another way: mathematical

Invariant: when a cell is popped, its recorded cost equals the true cheapest cost, because every other frontier route already costs at least as much and costs never decrease along a path (all step costs ≥ 0).

Explain it another way: applied

Ground robots plan on cost maps where each cell's cost reflects slope, roughness or distance from obstacles. Dijkstra and its goal-directed variant A* are standard choices for that kind of planning.

Try these examples

Example 1

Dijkstra on a cost grid (0 = wall), returning path, cost and cells expanded.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A path enters cells with costs 1, 1, 5, 5, 1, 1 (the start cell is free). What is its total cost?

Answer:

2. pq holds (7, A), (3, B), (5, C) via heapq. What does heapq.heappop(pq) return?

  • (7, A)
  • (3, B)
  • (5, C)
  • The last item pushed

3. On a map where every free cell costs 1, how do BFS and Dijkstra compare?

  • Dijkstra finds cheaper paths
  • Both find paths with the same cost (fewest moves); BFS avoids the heap's log factor
  • BFS finds cheaper paths
  • Dijkstra fails on uniform costs

4. An editor keeps an undo stack of waypoint ids: s = []; s.append(38); s.append(23); s.append(27); s.pop(); s.append(33); s.pop(); s.append(3); s.pop(). What value does the final s.pop() return?

Answer:

5. Why must Dijkstra's step costs be non-negative?

  • heapq can't store negative numbers
  • A finished cell's cost is assumed final; a negative step later could make a cheaper route to it
  • Negative numbers are slower
  • Python forbids them in tuples

Apply it

Term project, part 1. Build the planner package (grid.py, planners.py, tests). Both planners must take a GridMap and return (path, cost, expanded). Tests must include a corridor, a forced detour, an unreachable goal, and a map where Dijkstra's path is longer but cheaper than BFS's, each with an answer worked by hand.

Reflect

What cost would you put on each cell for a real rover, and where would those numbers come from?

Go further (online)

Project: measure the cost, plot it honestly

Your planner works on a 10 × 10 map. Will it still answer in time on a 200 × 200 warehouse? Don't guess: measure, model and plot.

About 50 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

The second half of the term project turns your planner into evidence. You'll run a fair experiment, fit what you see against what big-O predicts, and present it the way an engineering team would: plots that don't mislead, numbers with units, and limits stated plainly.

Goals

Predict

On open square maps, BFS from corner to corner expands every cell. If the side doubles from 50 to 100, roughly how do cells expanded change?

  1. Double
  2. Quadruple
  3. Stay the same
  4. Increase by 50

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, run your planners on open and obstacle maps with sides 25, 50, 100 and 200. For each, record cells expanded and the best of five times. Compute the time ratio for each doubling of the side. Which planner's growth is closer to what you predicted, and why might Dijkstra's be a little steeper?

What the interactive shows, in words

The Code Lab experiment can be followed from the worked numbers: on open maps with sides 25, 50, 100 and 200, BFS corner to corner expands 625, 2,500, 10,000 and 40,000 cells, an exponent of 1.0 against the number of cells. Times are measured as the best of five runs; plots use cells on the x-axis so linear growth appears straight.

Understand

Design the experiment

Question: how do runtime and cells expanded grow with map size for BFS and Dijkstra? Change only the size; fix the obstacle density, the start and goal positions, the random seed and the machine. Repeat each run and record the best or median time.

Choose honest axes

Plot against the number of cells V (not just side length) so linear growth looks linear. A log–log plot turns power laws into straight lines whose slope you can read. Label units, mark each measured point, and never join points you didn't measure with a smooth curve that implies more data.

Interpret, don't decorate

State the expected big-O, the measured exponent and the gap. Dijkstra's heap adds a log V factor and larger constants; Python overheads can dominate small maps. Finish with limits: one machine, one obstacle pattern, simplified robot (no size, turning cost or uncertainty).

Explain it another way: intuitive

You're the scientist now: your planner is the thing being tested, and the plots are your lab notebook.

Explain it another way: technical

Expected: BFS O(V); Dijkstra O(V log V) with a binary heap. Over a 64× range in V, log₂ V grows only from about 9 to 15, so Dijkstra's measured exponent should be a little above 1, not 2.

Explain it another way: mathematical

Estimate the exponent p from the slope of log T against log V; for one doubling of V, p ≈ log₂(T₂/T₁). Doubling the side quadruples V, so p ≈ log₄(T₂/T₁) per side-doubling.

Explain it another way: applied

Before deploying a planner on a real robot, teams benchmark it on maps larger than the target site, because the real environment is always bigger and messier than the test one.

Try these examples

Example 1

Count cells expanded by BFS on open maps and estimate the growth exponent against the cell count.

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. BFS expands all 3,600 cells of a 60 × 60 open map. How many cells would it expand on a 120 × 120 open map, corner to corner?

Answer: cells

2. Timing tests show a collision checker grows like n and takes 5 ms for n = 4096. Assuming that growth holds, predict its time for n = 8192, in ms.

Answer: ms

3. A program is scanning a sensor log. Its step count is measured with: count = sum(1 for i in range(36) for j in range(i)). What value does count hold?

Answer: steps

4. You plot time against map side length and see a curve bending upwards for BFS. What is the clearest honest fix?

  • Smooth the curve
  • Plot against number of cells (or use log–log axes) so O(V) shows as a straight line
  • Remove the largest map
  • Start the y-axis at the smallest time

5. Which is the best 'limitations' sentence for your report?

  • 'There are no limitations.'
  • 'Measured on one laptop with one 20% random obstacle pattern; the robot is modelled as a point with no turning cost, so real planning times will differ.'
  • 'The code might have bugs.'
  • 'Big-O is just a theory.'

Apply it

Term project, part 2 (deliverables). (1) Timing and cells-expanded measurements for BFS and Dijkstra on at least four map sizes. (2) Two plots: time against cells, and path cost (BFS vs Dijkstra) on obstacle maps; labelled, with units, all measured points shown. (3) A one-page interpretation: expected big-O, measured exponents, the gap, and the limits of your model.

Reflect

Which result in your experiment surprised you, and what explanation did you test for it?

Term assessment: engineering computation, end to end

A teammate's planner is correct, tested and painfully slow, and its chart says it's fast. Can you find every problem in fifteen minutes?

About 45 min · Checked by automated tests · Interactive lesson · Lite lesson (answers checked here)

Why it matters

Real engineering rarely asks one kind of question at a time. This review mixes the whole term: modules and objects, data structures, search and sort, growth rates, numerical methods and honest plots. Treat it as a code review of a teammate's work.

Goals

Predict

A planner stores visited cells in a list and calls 'cell in visited' for every neighbour. On a 100 × 100 open map, roughly how does that compare with using a set?

  1. About the same
  2. Roughly thousands of times more comparisons
  3. Slightly faster, because lists are simpler

Write down your guess and your reason. The reveal is in the online lesson.

Discover

In the Code Lab, review the worked example's planner_report function. List every problem you find under four headings: structure, correctness, efficiency, reporting. Fix them one at a time, re-running the tests after each fix.

What the interactive shows, in words

The Code Lab review can be done on paper: the 'before' function uses a list membership test inside a loop (O(n²)), divides by zero on an empty list and reports a number without unit, spread or sample size. The fixed version uses a set, checks for empty input, and reports median, standard deviation and n in milliseconds.

Understand

Review in layers

Structure: one job per function, clear modules, no hidden globals. Correctness: tests with hand-worked answers and edge cases. Efficiency: count the hot loop and check the containers. Reporting: units, n, spread, honest axes and stated limits.

Look for hidden loops

x in some_list, list.pop(0), list.index(x) and string concatenation in a loop all hide a scan. Inside another loop they turn O(n) into O(n²). A set, a deque, a dict or "".join usually fixes it.

Numbers need context

A result without units, sample size, spread or method is not yet evidence. A good review asks: how was this computed, how uncertain is it, and does the chart show it fairly?

Explain it another way: intuitive

Like a pit-stop check: tyres (structure), brakes (correctness), engine (efficiency), dashboard (reporting). Skip one and the car may still drive, until it doesn't.

Explain it another way: technical

Code review checklists catch more defects when they are specific: 'Is every membership test on a set or dict?', 'Does every function with a precondition check it?', 'Does every plot have labelled units?'.

Explain it another way: applied

Most engineering teams require at least one reviewer to approve a change before it is merged, and reviewers routinely check performance assumptions and charts as well as logic.

Try these examples

Example 1

Review this function. What's wrong, and what does the fixed version look like?

The worked solution is in the online lesson.

Common mix-ups

Practice questions

Questions only. Check your answers in the Lite lesson; they are graded on our server and nothing is saved.

1. A program is comparing every pair of waypoints. Its step count is measured with: count = sum(1 for i in range(0, 266, 10)). What value does count hold?

Answer: steps

2. A sorted list holds 8 waypoint ids. Binary search compares the target with one middle element per loop and halves the range each time. In the worst case (including a target that is not there), how many elements does it compare with the target?

Answer: comparisons

3. Bisection starts from the bracket [1, 3] and stops once the bracket width is at most 0.001. What is the smallest number of steps that guarantees this?

Answer: steps

4. Part masses (g) arrive as a = [58, 46, 38, 32, 28]. They are sorted with insertion sort, where each new key moves left while j >= 0 and a[j] > key. Counting every evaluation of a[j] > key, how many comparisons are made?

Answer: comparisons

5. A log of motor temperature (°C) reads xs = [42, 50, 49, 47, 47, 44, 43, 44, 47]. What is the mean, statistics.mean(xs)? Give 2 decimal places.

Answer:

6. Which line inside a loop over n items makes the whole loop O(n²)?

  • total += x
  • queue.popleft() on a deque
  • if x in seen_list:
  • seen_set.add(x)

7. You need a root of a smooth f on [1, 2] (with a sign change) to 10⁻¹² quickly and safely. Best approach?

  • Bisection only
  • Newton from an arbitrary guess
  • Bisection to get close, then Newton, rejecting Newton steps that leave the bracket
  • Guess and check by hand

Apply it

Term assessment. Hand in your finished term project (planner package, tests, measurements, two plots, interpretation) together with a one-page review of a classmate's project (or the worked example) under the four headings. Assessed with the term rubric: correctness, software structure, efficiency analysis, visual communication.

Reflect

Which idea from this term will change how you write code next term, and why?