Algorithm foundations · Lab catalogue
Small algorithms, visible decisions
Download the two original files to the same practice folder: Python lab · 24-test companion. Read the explanation and predict outputs before running. Keep the original files and edit a separate practice copy.
Original practice extension for Amit’s Library. Python 3.9+ and its standard library only. This is a bridge from the existing algorithm foundations to explicit beginner recursion, elementary sorting and first-match binary search. It does not replace the existing recursive dependency model in labs/people_planning.py, or imply complete coverage of the supplied course.
Before running
Keep algorithm_extension.py and algorithm_extension_test.py together in a practice folder. Use synthetic values only. No installation, account, network access or system change is required.
python3 algorithm_extension.py
python3 -m unittest -v algorithm_extension_test
The lab accepts list/tuple inputs of at most 256 items. Numeric values are integers, excluding booleans and floats; records are (integer_priority, string_label) tuples. The single-branch recursive sum allows at most 64 items. These are teaching limits, not general algorithm constraints. Functions preserve their inputs and return results separately. Python may write ordinary bytecode cache files when imports run; PYTHONDONTWRITEBYTECODE=1 can suppress them in a compatible shell. The examples themselves perform no file writes.
1. State the contract and predict
A fictional print team has adjustments [6, -2, 5, 1]. Here they are abstract signed counts, not a money or inventory ledger. Predict the total 10 before running three methods. An empty sequence totals 0. A one-value sequence totals that value.
For the iterative method, after processing the first k elements, the accumulator equals their sum. Each loop processes one previously unprocessed value. This links a result contract, an invariant and a termination argument. Try an all-negative input; a correct sum should not silently discard negative adjustments.
2. One recursive branch
sum_recursive uses an index into one copied input. At the end of the input it returns 0. Otherwise it adds the current element to the result for the remaining suffix. Its decreasing measure is the number of unprocessed elements.
For [6, -2], write the calls before the returns:
visit(0) waits for 6 + visit(1)
visit(1) waits for -2 + visit(2)
visit(2) returns 0
visit(1) returns -2
visit(0) returns 4
A terminating mathematical definition still consumes interpreter stack. Do not raise the recursion limit to force this exercise through large inputs. The 64-item cap keeps normal demonstrations modest but cannot guarantee success inside an already deep call stack. The iterative alternative avoids this recursive depth. See Python’s recursion-limit reference.
3. Two branches do not automatically mean exponential work
sum_divide handles a half-open interval [lo, hi). An empty interval returns 0; a single-item interval returns that item. A larger interval splits into disjoint halves, sums both and combines the results. No recursive list slices are created.
For [6, -2, 5, 1], draw [0,4) splitting into [0,2) and [2,4), then into four singleton intervals. Their returns are 6, -2, 5, 1; the halves return 4 and 6; the root returns 10. For positive length n, this version has n leaves and n-1 internal calls. The work is linear in item count under a constant-cost arithmetic model, not exponential. The deepest path grows logarithmically. Compare with the single-branch method’s linear-depth path. The input copy still costs linear space in both wrappers. Python integer-operation costs also grow with integer size, which this introductory model sets aside.
Next inspect people_planning.py: its recursive dependency traversal adds memoization and cycle checks. Why are those useful for a graph but unnecessary for these disjoint index ranges?
4. Sort a key without losing a record
Jobs arrive as [(2,"A"), (2,"B"), (1,"C")]. Lower priority numbers come first in this invented rule. Labels identify records but are not sorting keys. This numerical rule is not a claim about fair service scheduling.
Bubble sort compares adjacent priorities, swapping only when the left is greater. After a full pass, a largest remaining priority is at the right boundary. A pass with no swaps ends the algorithm.
Selection sort locates a smallest remaining priority and swaps it into the next position. It returns C,B,A for the fixture: the long swap reverses the equal-key A/B arrival order. The result is sorted but this implementation is not stable.
Insertion sort takes the next record and shifts strictly larger preceding priorities rightward. Its already-processed prefix remains sorted. Equal priorities are not shifted past each other, so it returns C,A,B, as does bubble sort.
Stability means retaining original order among equal keys, not merely producing ordered keys. Our tests verify both sorted priorities and the multiset of complete records. Python’s built-in sorting is stable and is preferable for ordinary application work; these small implementations expose mechanics. See Python sorting. For algorithm study, see CS50’s sorting and recursion notes and MIT’s insertion-sort lecture.
For these implementations, bubble and insertion sorts have linear best-case comparison work on already sorted data and quadratic worst-case work. Selection sort examines a quadratic number of candidate pairs even if sorted already. All three public functions make an input copy, so none has constant total auxiliary space. This exercise’s 256-item cap is intended for inspection, not benchmarks.
5. Find the first match, not just a match
For sorted [-3,2,2,8], the first 2 has index 1, while 4 is absent and returns -1. _lower_bound narrows a half-open range. Before each step, excluded values left of lo are less than the target, and excluded values at/after hi are at least the target. A comparison either advances lo beyond the middle or moves hi to it. The range shrinks.
Trace target 2: (lo,hi,mid)=(0,4,2), then (0,2,1), then (0,1,0); the final insertion point is 1. An insertion point can also denote absence, so the wrapper checks equality and range. This distinction matches the purpose explained in Python’s bisect documentation.
Important: the public binary_first copies and validates all input values and sorted order on every call. The search core uses logarithmically many comparisons, but the checked wrapper takes linear time and space. Do not advertise its total cost as logarithmic. For repeated queries, a later exercise could validate a fixed immutable dataset once, with a clear invalidation rule if it changes.
Optional companion reading: Public lecture: depth-first, hill climbing and beam search. Draw a small search tree. Trace the first three expansions with depth-first search and then with a beam of width two using your own node scores. Unlike binary search, the example explores branches rather than narrowing a sorted range.
6. Submit evidence, not just a successful run
Submit the hand traces, a table of each function’s input/output/error contract, the unchanged original fixtures, and test results. Explain the A/B stability difference and the wrapper/core complexity distinction.
The 24 test methods include small exhaustive checks for all 364 sequences of length 0–5 over {-1,0,1}, plus hand-calculated examples, invalid inputs, bounds and preservation. They do not establish correctness for every input or environment. Test expectations use independent hand values and standard-library oracles, not copies of the implementation.
For undergraduate work, justify termination and the record-preservation contract. For postgraduate work, compare the real end-to-end costs and propose a reusable validated-search interface. For research practice, design an evaluation with specified data sizes, distributions, hardware and repeated measurements; do not infer general performance from this capped toy lab. An extension is complete only when its claims, tests and limitations agree.
Source and reuse note
The code, fixture values, traces and exercises here are original. Sources above support general concepts and language behaviour; no university assignment, lecture asset or LMS export is redistributed. Institution links do not imply affiliation or syllabus equivalence.