A4 Python for engineers · Practice
Sorting
Problems dealt one at a time, with new numbers every time. The kinds you miss come back more often, and you can keep going as long as you like.
Check
Write insertion_sort(a) returning a new sorted list and the number of comparisons it made, as (result, comparisons), counting each a[i] > key test. Set s, c = insertion_sort(x) for the starter's random list of n = 8 values, and c_rev to the comparisons for the list list(range(n, 0, -1)).
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write merge(a, b) that merges two sorted lists into one sorted list in a single pass, taking from a when the front items tie, without calling sort or sorted. Set m = merge(a, b) for the starter's lists.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Using your merge, write the recursive merge_sort(x) and count the comparisons it makes in total. Set s, c = merge_sort(x) for the starter's random list of n = 10 values, and bound to .
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Each part in the starter is (package, ohms, tolerance_pct). Set ordered to the list sorted by package alphabetically, then by tolerance from tightest to loosest, then by resistance from largest to smallest, using one call to sorted with a tuple key.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Write percentile(x, p) returning the nearest-rank pth percentile of a list: sort it and take item number , counting from 1. Set q = percentile(delays, p) for the starter's 200 delays and p = 50.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Insertion sort is given a list of 50 distinct items in reverse order. How many comparisons does it make?
Check
Set by_len to the starter's words sorted by length, shortest first, with words of equal length kept in their original order.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
Check
Use bisect.insort to add v = 47 to the sorted list xs so it stays sorted, then set pos to the index where it landed using bisect.bisect_left.
Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.
A kind of problem counts as solid once you've got it right on the first try twice in a row. Back to the lesson · Practice every topic in A4