Objectives and prerequisites
By the end of this course, you will be able to turn a vague need into a precise problem, describe a solution step by step, translate it into Python 3 and verify that it gives the right result on ordinary and edge cases. The common thread is a list of orders: calculate their totals, find those above a threshold and sort them.
Prerequisites: use a terminal and run a Python file. No advanced mathematics is required. The examples use Python 3.12 but remain valid on 3.10 and later. The goal is not to learn the whole Python library: it is to learn to reason before writing code.
Path: chapters 1 to 4 establish the problem, variables, conditions and loops; chapters 5 to 8 cover collections, functions, search and sorting; chapters 9 to 12 cover correctness, cost, debugging and synthesis. Expect about twenty-five minutes of reading and three to four hours of practice.
Convention: amounts use Decimal, never float, to avoid rounding errors. Examples run in a file named orders.py. Datasets are fictional. Each chapter ends with a check you can reproduce.
1. Problem, inputs, output and constraints
An algorithmic problem has three parts: input data, expected output and constraints. "Calculate the order total" is ambiguous: total of what, for which period, with or without tax, and what to do with a cancelled order? Until these questions are answered, the code may be technically correct but wrong for the business.
Formalising means writing the answers in plain language, then turning them into testable rules. For example: an order has an identifier, a status and a list of lines; each line has a unit price and a quantity; only validated orders count; the total is the sum of prices multiplied by quantities. An ambiguous rule must be flagged, not guessed.
Input: a list of orders, each with a status and lines.
Output: the total of validated orders, in euros, rounded to the cent.
Constraints:
- prices are positive or zero;
- a quantity is a strictly positive integer;
- a cancelled or draft order is ignored;
- the result must never be negative.
Constraints also include practical limits: list size, missing values, duplicates, unexpected characters. An algorithm that works on three orders may fail on a hundred thousand. Before writing a loop, ask what happens with an empty list, a single line or a zero amount.
A set of examples acts as a contract. Write by hand the input and expected output for two or three cases, including an edge case. These examples become tests. If you cannot calculate the result by hand, you cannot verify the program. Code does not replace understanding the problem.
Finally, distinguish the problem from the solution. "Find the most expensive order" is a problem; "walk the list and keep the maximum" is a solution. Several solutions may solve the same problem at different costs. Start with a correct, readable solution, then improve it if necessary. Premature optimisation often produces incomprehensible code.
Writing examples before code forces you to clarify the rules. If the business says "recent orders", ask for a start date, an end date and a time zone. If nobody can answer, choose an explicit convention, document it and have it validated. A correct algorithm on a wrong rule is still wrong; clarity of specification is part of algorithmic work and of overall software quality and clarity.
Write the problem statement where the code will live, not only in a meeting note. The statement should fit on one screen: inputs, output, rules, edge cases and examples. When the code and the statement disagree, one of them is wrong, and the disagreement is visible. A statement that changes during implementation is a sign that the problem was not understood; update it deliberately and record why.
2. Variables, values, types and expressions
A variable is a name associated with a value. In Python, the name is created by assignment: total = 0. The value has a type: integer, string, boolean, list, dictionary, Decimal object. The type determines possible operations and operator behaviour. 1 + 2 gives an integer, "1" + "2" gives the string "12".
Tracking state means writing the value of each variable after each step. For total = 0, then total = total + 10, the state becomes total = 10. This manual tracking looks childish, but it reveals most logic errors before execution. A state table is more reliable than intuition.
from decimal import Decimal
price = Decimal("12.50")
quantity = 3
total = price * quantity
print(total) # 37.50
print(type(total)) # <class 'decimal.Decimal'>
Names must describe content: valid_total is better than t. Avoid names whose meaning changes during the program. A variable that sometimes holds a list and sometimes None makes reasoning difficult. If a value may be absent, represent that case explicitly and document the rule.
Expressions combine values and operators. Pay attention to precedence, parentheses and conversions. int("12") converts a string to an integer but fails if the string contains anything else. Decimal("0.1") is exact, while Decimal(0.1) starts from an already approximate float. For amounts, always build the Decimal from a string.
Booleans are True or False. In Python, several values are considered false in a boolean context: 0, "", [], {}, None. This flexibility is convenient but can hide missing data. Prefer an explicit comparison when the difference between "empty" and "absent" matters.
Finally, a variable is not a box containing a value, but a name referencing an object. For mutable objects such as lists, two names may reference the same list; modifying one modifies the other. This distinction explains surprising bugs and justifies copying explicitly when independent state is required.
3. Conditions, boolean logic and boundaries
A condition chooses an execution path. if, elif and else evaluate boolean expressions in order. The first true condition runs; later ones are ignored. Order matters: if you test total > 0 before total > 100, the second case is never reached for 150 when the first branch contains an else or a return.
def category(total):
if total < 0:
raise ValueError("negative total")
if total == 0:
return "empty"
if total < 50:
return "small"
if total < 200:
return "medium"
return "large"
Boundaries are a classic source of errors. Does 50 belong to "small" or "medium"? The answer must come from the requirement, not chance. Write a case table with boundary values: -1, 0, 49, 50, 199, 200. For each value, state the expected result. This table becomes both a test and documentation.
Boolean logic combines conditions with and, or and not. and is true only if both operands are true; or is true if at least one is. Python evaluates lazily: in a and b, b is not evaluated if a is false. This enables guards such as items and items[0], but can also hide a side effect.
Chained comparisons, such as 0 < total <= 100, are readable and equivalent to 0 < total and total <= 100. Beware of types: comparing a string and a number raises an error in Python 3, which is preferable to a silent conversion. Validate inputs before comparing.
A complex condition benefits from a name. is_valid_order(order) is clearer than five nested conditions. The function can be tested separately. If the rule changes, only one place needs updating. Readability is not a luxury: it reduces maintenance errors.
Finally, avoid redundant or contradictory conditions. An if total > 100 followed by elif total > 50 is correct, but an if total > 50 followed by elif total > 100 makes the second branch partly useless. Reread the case table to verify that each interval is covered exactly once.
Guard clauses keep conditions flat. Instead of nesting an entire function inside if valid:, return early when the input is invalid. The main path then stays at one indentation level, which makes it easier to read and test. A guard clause must produce a clear outcome: an exception, a default value or a documented absence. Do not use it to hide an error that should stop the program.
4. Loops, accumulators and termination
A loop repeats an operation over a collection or until a condition. for item in collection traverses elements; while condition repeats while the condition is true. For a known collection, prefer for: termination is guaranteed by the collection size. For a condition, ensure something changes on each iteration, otherwise the loop is infinite.
def order_total(orders):
total = Decimal("0.00")
for order in orders:
if order["status"] != "validated":
continue
for line in order["lines"]:
total += line["price"] * line["quantity"]
return total
An accumulator is a variable initialised before the loop and updated on each iteration. Initialisation must match the operation: 0 for a sum, 1 for a product, None or a sentinel for a maximum. An initialisation error gives a wrong result even when the loop is correct.
Termination of a while loop is demonstrated: identify a quantity that moves toward the stop condition. For example, while remaining > 0 with remaining -= 1 terminates if remaining is a positive integer. If remaining can be negative or the decrement is conditional, termination is no longer guaranteed. Add a safety limit and test it.
Nested loops have a cost. Traversing each order then each line is often necessary, but traversing the whole list for each element gives quadratic cost. Before nesting, ask whether an indexed structure, such as a dictionary, could retrieve the information in one lookup.
break and continue control flow. break exits the loop; continue moves to the next iteration. Used sparingly, they clarify; used everywhere, they make flow hard to follow. Prefer an explicit condition when possible.
Finally, test edge cases: empty list, one element, all elements filtered, zero quantity if allowed. A loop that never runs must return the correct initial value. For a sum, zero; for a maximum, an explicit absence rather than an arbitrary value.
5. Lists, dictionaries and data representation
A list is an ordered sequence, indexed from 0 to len(items) - 1. A dictionary maps keys to values and allows fast lookup by key. The choice of structure affects readability and cost. A list of orders is traversed; a dictionary indexed by identifier retrieves an order without scanning the list.
orders = [
{"id": 1, "status": "validated", "lines": [{"price": Decimal("12.50"), "quantity": 2}]},
{"id": 2, "status": "draft", "lines": []},
]
index = {order["id"]: order for order in orders}
print(index[1]["status"]) # validated
Represent data with consistent types. A price is a Decimal, a quantity an integer, a status a string from a known set. If statuses are numerous, a constant or enumeration prevents typos. Data that may be absent must be represented explicitly, for example by None, not by an ambiguous empty string.
Dictionaries are mutable: adding or changing a key changes the object. Iterating over a dictionary while modifying it may raise an error. Iterate over a copy of the keys when necessary. For lists, slicing items[1:3] returns a new list; list.sort() sorts in place, while sorted(list) returns a sorted copy.
Nested structures quickly become hard to read. If a function receives a five-level dictionary, extract functions or objects. The goal is not to avoid dictionaries, but to keep each level understandable. A data schema written before the code helps choose keys and types.
List comprehensions, such as [o for o in orders if o["status"] == "validated"], are concise and readable for a simple transformation. Avoid complex nested comprehensions: an explicit loop is often clearer. Conciseness is useful only when it does not hide intent.
Finally, do not confuse an empty list with missing data. [] means "no orders"; None means "information not provided". Treating them the same may hide an import error. Document the convention and test both cases.
Copying a collection has a cost and a meaning. A shallow copy duplicates the outer list but shares nested dictionaries; a deep copy duplicates everything. Most bugs come from modifying a nested object through a shallow copy while believing it was independent. Decide whether you need independence or sharing, and name the operation accordingly. For small data, clarity matters more than the copy cost.
6. Functions, parameters, return and scope
A function groups a responsibility and gives it a name. It receives parameters, performs a calculation and returns a result with return. A function with no explicit return returns None. Prefer functions that return a value over functions that modify global variables: they are easier to test and reuse.
def line_total(line):
return line["price"] * line["quantity"]
def order_total(order):
return sum((line_total(line) for line in order["lines"]), Decimal("0.00"))
def valid_total(orders):
return sum(
(order_total(o) for o in orders if o["status"] == "validated"),
Decimal("0.00"),
)
Parameters may have default values, but avoid mutable defaults such as [] or {}: they are created once and shared between calls. Use None then create a new list inside. This trap is classic and produces results that seem random.
Scope determines where a name is visible. A variable created inside a function is local; a global variable must be declared global to be modified, which is rarely a good idea. Prefer passing values as parameters and returning results. This makes dependencies explicit and tests independent.
Decompose by responsibility, not by line count. line_total, order_total and valid_total express three calculation levels. Each function can be tested separately. A fifty-line function that does everything is hard to understand and fix.
Functions may raise exceptions to signal invalid input. ValueError suits an incorrect value, TypeError an unexpected type. Do not hide an exception with an overly broad except: you lose the information needed for diagnosis. Let the caller handle what it must.
Finally, document the contract: what the function expects, what it returns and what it may raise. A short docstring is often enough. The contract lets you replace the implementation without breaking callers and guides tests.
7. Linear search and binary search
Linear search scans a collection until it finds the element or exhausts the list. It works on an unsorted collection and costs O(n) in the worst case. It is the default search when data is small or order is not guaranteed.
def find_order(orders, identifier):
for order in orders:
if order["id"] == identifier:
return order
return None
Binary search applies only to a sorted collection. It compares the target with the middle value, then discards the half that cannot contain the answer. It costs O(log n), but sorting first costs O(n log n). If you search once, linear search may be faster; if you search often, sorting then binary search pays off.
def binary_search(sorted_values, target):
start, end = 0, len(sorted_values) - 1
while start <= end:
middle = (start + end) // 2
if sorted_values[middle] == target:
return middle
if sorted_values[middle] < target:
start = middle + 1
else:
end = middle - 1
return -1
Binary search boundaries are delicate. start <= end, middle + 1 and middle - 1 must be consistent. An off-by-one error can cause an infinite loop or miss the element. Test with an empty list, one element, two elements, a target smaller than all and larger than all.
Dictionary lookup is even faster in practice, O(1) on average, if the key is available. Building the index costs O(n) once, then each lookup is direct. This is often the best choice for retrieving orders by identifier. Binary search remains useful when data is already sorted and an index would cost too much memory.
Do not confuse "found" with "default value". Returning None for absence is acceptable if the caller handles it. Returning 0 or an empty string may be confused with a real value. The function contract must state clearly what is returned when the item is absent.
8. Sorting and comparison with the library
Sorting orders a collection according to a criterion. A simple algorithm such as insertion sort is easy to understand and prove. It scans elements and inserts each into its place in the already sorted part. Its cost is O(n²) in the worst case, which is fine for small lists but slow for large ones.
def insertion_sort(values):
result = list(values)
for i in range(1, len(result)):
current = result[i]
j = i - 1
while j >= 0 and result[j] > current:
result[j + 1] = result[j]
j -= 1
result[j + 1] = current
return result
In Python, sorted and list.sort use Timsort, a stable and efficient algorithm, O(n log n) in the worst case. For real use, use the library. Understanding a simple sort helps reason about invariants, but reimplementing Timsort is not the goal. The library is tested, optimised and maintained.
Sorting can be customised with a key: sorted(orders, key=lambda o: o["total"], reverse=True). The key must be stable and comparable. Sorting by several criteria can use a tuple, such as (status, -total). Beware mixed types: comparing None and a number raises an error.
Sorting is stable if two equal elements keep their relative order. This is useful for successive sorts: sorting by date then by status preserves date order within each status. Timsort is stable; selection sort is not necessarily. Verify the property if your logic depends on it.
Sorting cost also includes memory. In-place sorting modifies the list and uses little extra memory; sorted returns a new list. For large volumes, the difference matters. Measure with representative data rather than assuming.
Finally, do not sort if you do not need order. Finding a maximum, minimum or value by key can be done in one pass, O(n), without sorting. Sorting is useful when several ordered reads are needed. Choose the algorithm based on use, not reflex.
Sorting criteria must be total enough to avoid ambiguity. If two orders have the same total, the order between them is unspecified unless you add a tie-breaker such as the identifier. An unstable or incomplete sort can make a report change between runs, which complicates comparisons and tests. Add a deterministic secondary key when the output is user-visible or used by another process.
9. Correctness, invariants and edge-case tests
An algorithm is correct if it produces the expected result for all valid inputs, not only the examples tried. A passing test shows that one case works; it does not prove general correctness. To go further, identify an invariant: a property true before and after each iteration that implies the result at the end.
For the sum of validated orders, the invariant may be: "after processing the first k orders, total contains the sum of validated orders among those k orders". Initially, k = 0 and total = 0. Each iteration adds the current order if validated and changes nothing otherwise. At the end, k = n and the total is complete.
Tests must cover nominal cases, edge cases and error cases. Nominal: several valid orders. Edge: empty list, one order, zero amount, quantity of one. Error: negative price, zero quantity, unknown status. A test that checks only the nominal case gives false assurance.
def test_valid_total():
orders = [
{"status": "validated", "lines": [{"price": Decimal("10.00"), "quantity": 2}]},
{"status": "draft", "lines": [{"price": Decimal("99.00"), "quantity": 1}]},
]
assert valid_total(orders) == Decimal("20.00")
assert valid_total([]) == Decimal("0.00")
A test must fail if behaviour changes. To verify that a test is useful, break the code deliberately and observe the failure. A test that always passes tests nothing. Assertions must target observable results, not implementation details.
Finally, distinguish specification errors from implementation errors. If the requirement says "all orders" and the code filters validated ones, the test can be green and the result wrong. Correction starts with the specification. Write the rules, have them validated, then test the code against them.
A useful test suite is fast, deterministic and readable. Avoid dependencies on randomness, the current time or the network. If a test depends on a date, inject it as a parameter. A slow or flaky test is eventually ignored, and regressions return. Prefer a few targeted, maintained tests over a large suite nobody dares to run.
Name tests after the behaviour they protect, not after the function. test_empty_list_returns_zero explains the guarantee; test_total_2 does not. When a test fails, the name should tell you which rule broke. Group related cases and keep one reason to fail per test. A test that asserts five unrelated things makes diagnosis slower and encourages people to skip it.
10. Time and memory cost
O notation describes how cost grows as input size increases. O(1) means constant cost; O(n) linear growth; O(n²) quadratic; O(log n) logarithmic. These notations ignore constants, but they predict behaviour on large inputs. An O(n²) algorithm may be faster than O(n log n) on a small list, then become much slower.
n = 1,000
O(n) : ~1,000 operations
O(n log n): ~10,000 operations
O(n²) : ~1,000,000 operations
n = 100,000
O(n) : ~100,000
O(n log n): ~1,700,000
O(n²) : ~10,000,000,000
Memory cost matters too. A list copy doubles memory use; a dictionary index adds a structure. For large volumes, an O(n) memory operation may be more problematic than an O(n log n) in-place sort. Measure both dimensions, not only time.
Nested loops are often O(n²). Traversing all orders for each order to find a duplicate is quadratic; a dictionary of seen identifiers reduces cost to O(n). This kind of improvement is more useful than a syntax micro-optimisation. Look for the right data structure first.
The worst case is not always the real case. Linear search may find the element on the first try, but we describe the worst case to guarantee a bound. Distinguish best, average and worst case. For an application, the worst case often determines the experience of the unlucky user.
Finally, measure before optimising. time.perf_counter or the timeit module give reproducible measurements. An unmeasured optimisation may hurt readability without real gain. Note data size, machine and Python version. A result without context is not proof.
A profiler such as cProfile shows where time is actually spent. It avoids optimising a secondary function while leaving the main bottleneck intact. Use it on a representative scenario, then measure again after the change. An optimisation that does not move the profiler probably did not solve the problem.
Space complexity counts the extra memory an algorithm needs beyond its input. Reversing a list in place is O(1) extra space; building a reversed copy is O(n). Recursion adds a call stack whose depth can become the limiting factor. For large inputs, an algorithm with good time complexity but excessive memory use may fail before it finishes. State both dimensions when you justify a choice, because a fast algorithm that exhausts memory is not usable.
11. Debugging and logic errors
A bug may be a syntax error, an exception or a logic error. Syntax is reported by the interpreter; an exception gives a trace and a type. Logic errors are harder: the program runs but the result is wrong. Tests, state tracking and code reading are the main tools.
Start by reproducing the bug on a minimal case. Reduce the data, isolate the function, check inputs. A bug appearing on a hundred orders can be reproduced with two. Add assertions or temporary prints, then remove them. The goal is understanding, not accumulating traces.
def valid_total(orders):
total = Decimal("0.00")
for order in orders:
if order["status"] != "validated":
continue
for line in order["lines"]:
total += line["price"] * line["quantity"]
return total
# Check inputs before suspecting the loop:
# print(orders)
Frequent logic errors are incorrect initialisation, an inverted condition, an excluded boundary, a reused variable, modifying a list during iteration and confusing None with a value. Read the code aloud while following the data. A second person often sees what the author no longer sees.
Floats pose a specific problem for prices. 0.1 + 0.2 does not give exactly 0.3 in binary. For amounts, use Decimal and round explicitly to the cent with quantize. Do not compare floats with ==; use a tolerance if you must work with them.
Finally, fix the cause, not the symptom. Adding an if to avoid a special case may hide a modelling error. Ask why the case occurs. A fix that increases complexity without explanation is probably incomplete. Add a non-regression test for each bug fixed.
12. Synthesis: build and verify a complete process
The common thread brings the skills together: read a list of orders, filter statuses, calculate totals, search by identifier and sort by amount. Each step has a contract, edge cases and a cost. The final program is not a sequence of magic lines: it is a decomposition into verifiable responsibilities.
from decimal import Decimal
def order_total(order):
return sum((l["price"] * l["quantity"] for l in order["lines"]), Decimal("0.00"))
def validated_orders(orders):
return [o for o in orders if o["status"] == "validated"]
def valid_total(orders):
return sum((order_total(o) for o in validated_orders(orders)), Decimal("0.00"))
def find_order(orders, identifier):
return next((o for o in orders if o["id"] == identifier), None)
def sort_by_total(orders):
return sorted(orders, key=order_total, reverse=True)
To verify, build a dataset with a validated order, a draft, a cancelled one, an empty list and a zero amount. Calculate results by hand. Write tests. Measure time on a generated list of ten thousand orders. Compare linear search and an identifier index.
Justify your choices: Decimal for amounts, a list to preserve order, a dictionary for the index, sorted for stability and performance. Explain the cost of each operation and the reason for the choice. An unjustified choice is debt for the person maintaining the code.
To go further, test properties: the total is always positive or zero, sorting loses no element, search returns None for an absent identifier. Property-based tests complement examples. They do not prove everything, but they explore more cases.
Finally, keep the code simple. A readable, correct solution is better than a clever, fragile one. Complexity must be justified by a measured need. Algorithmics is not the art of writing as much code as possible: it is the art of choosing the representation and steps that make the problem solvable and verifiable.
Have someone else read the final code with the problem statement in hand. They should be able to explain what each function promises and find the edge cases in the tests. If they cannot, the code or the statement is incomplete. A short review catches naming problems, hidden assumptions and missing cases before they reach production.
Exercise 1 — Formalise
A cooperative sells products to its members. It wants the total amount of paid orders for the month, excluding cancelled orders. Write the inputs, output, constraints and three test cases, including an edge case.
Solution
Input: a list of orders with date, status and lines (price, quantity). Output: an amount in euros, rounded to the cent. Constraints: only orders from the month with status "paid" count; prices and quantities are positive; an empty list gives zero. Cases: two paid orders, one cancelled order ignored, one order outside the month ignored, an empty list. The edge case is the empty list and the zero-amount order.
Exercise 2 — Conditions and boundaries
Write a function that classifies an amount as "empty", "small" (0 to 50 excluded), "medium" (50 to 200 excluded) and "large" (200 and above). Give the case table for -1, 0, 49.99, 50, 199.99 and 200. What should happen for a negative amount?
Solution
The function raises ValueError for a negative amount. 0 gives "empty", 49.99 "small", 50 "medium", 199.99 "medium", 200 "large". The case table documents each boundary and removes ambiguity. A negative amount is invalid input, not a business category; it must be rejected explicitly.
Exercise 3 — Loops and accumulation
Write a function that calculates the total of an order's lines, then the total of validated orders. Test with an empty list, an order with no lines and a quantity of one. Explain the accumulator initialisation.
Solution
The order total initialises Decimal("0.00") and adds price * quantity for each line. The global total also initialises to zero and adds each validated order total. An empty list returns zero; an order with no lines returns zero. Initialising to zero is the neutral element of addition, ensuring the empty loop produces the correct result.
Exercise 4 — Lists and dictionaries
From a list of orders, build an index by identifier, then retrieve an order by identifier without scanning the list. What happens if two orders share the same identifier? How can you detect it?
Solution
The index is a dictionary {o["id"]: o for o in orders}. Lookup is direct. If two identifiers are identical, the last order overwrites the previous one. To detect the duplicate, check if o["id"] in index before inserting and raise an error or log the conflict. An identifier must be unique; the duplicate reveals a data problem.
Exercise 5 — Search and sort
Implement a linear search by identifier and a binary search on a sorted list of identifiers. Compare their cost and explain when to use each. Test an absent target.
Solution
Linear search is O(n) and works without sorting. Binary search is O(log n) but requires a sorted list. For a single search on a small list, linear is enough; for repeated searches, sorting then binary search or building an index becomes worthwhile. An absent target must return None or -1 according to the contract, never an ambiguous value.
Exercise 6 — Cost and tests
Generate a list of 10,000 orders, measure the time of a linear search and an index lookup. Add tests for an empty list, one order and an absent identifier. Explain why a passing test does not prove general correctness.
Solution
Linear search scans up to 10,000 elements; the index is built once and then answers in average constant time. Measurements must be repeated and compared on the same machine. Tests cover edge cases but do not prove every possible case; they increase confidence and detect regressions. A proof or invariant complements tests.
Capstone — complete process
Deliver a program that loads a list of orders, filters validated ones, calculates totals, searches by identifier and sorts by descending amount. Add input validation, edge-case tests, a timing measurement on 10,000 orders and a note explaining the structure and cost choices.
Grid: rules are explicit; amounts use Decimal; functions have clear contracts; empty and invalid cases are handled; tests fail if behaviour changes; measurement is reproducible; choices are justified. A program without tests or justification is not complete.
Common errors and debugging method
Confusing problem and solution, guessing an ambiguous rule, initialising an accumulator in the wrong place, inverting a condition, missing a boundary, modifying a list during iteration and using float for prices are classic errors. An overly long function and unclear names make every other problem worse.
Method: reproduce on a minimal case, check inputs, track state step by step, formulate an invariant, then fix the cause. Add a non-regression test. If the result is wrong, compare expected and actual results at each step, not only at the end.
Self-assessment
You should now be able to formalise a problem, choose a data structure, write a terminating loop, explain an invariant, distinguish linear and binary search, use a library sort, estimate O(n) or O(n²) cost and test edge cases.
Self-assessment: I can write the rules before the code; I can track an accumulator's state; I can explain why Decimal is preferable to float; I can test an empty list; I can justify an index or a sort. To progress, study data structures, amortised complexity and property-based testing.
References
- Python — The Python Tutorial, consulted on 23 October 2026.
- Python — decimal, consulted on 23 October 2026.
- Python — timeit, consulted on 23 October 2026.
- MIT OCW — Introduction to Algorithms, consulted on 23 October 2026.
- Invariant — general reference, consulted on 23 October 2026.