ML Foundations

Use bisect with a key for sorted records

Search by a comparable key and insert a whole record without confusing the two inputs.

Example results for Use bisect with a key for sorted records. equal-score range: 1 3
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

Search using the extracted key

When records are sorted by a field, bisect_left and bisect_right use the key function on list elements, but do not apply it to the search target. Pass a target comparable to the extracted field, not an arbitrary record. The key parameter was added in Python 3.10. [1]

For example, use the integer score 4 when records are tuples whose second field is an integer. A tuple as the search target would require comparing an integer with a tuple in this fixture, producing a TypeError.

References: [1]

Find the equal range and insert a record

Run python examples/python_bisect_key_search.py. The left and right insertion points identify the half-open range of records with score 4. The fixture uses a list already sorted by the same key, a necessary precondition for interpreting these positions. [1, 2]

insort_left takes the whole new record, applies its key for searching and inserts that record before the existing equal-score records. The example also catches the incompatible whole-record search target. Assertions check the two boundaries and the insertion position. [1]

Executed with Python 3.12.14; stdout and checksum are recorded in private evidence.

from bisect import bisect_left, bisect_right, insort_left

rows = [('a', 2), ('b', 4), ('c', 4), ('d', 8)]
key = lambda row: row[1]
left = bisect_left(rows, 4, key=key)
right = bisect_right(rows, 4, key=key)
print('equal-score range:', left, right)
print('matching records:', rows[left:right])
insort_left(rows, ('new', 4), key=key)
print('after insert:', rows)
assert (left, right) == (1, 3)
assert rows[1] == ('new', 4)
try:
    bisect_left(rows, ('probe', 4), key=key)
except TypeError:
    print('whole-record probe: TypeError')
else:
    raise AssertionError('expected a type mismatch')

Recorded output

equal-score range: 1 3
matching records: [('b', 4), ('c', 4)]
after insert: [('a', 2), ('new', 4), ('b', 4), ('c', 4), ('d', 8)]
whole-record probe: TypeError

References: [1], [2]

Respect the scope of the search

Sort by the same key before searching; a key function extracts a comparison value but does not sort the input. Choose left or right according to the intended position among equal values. [1, 2]

The example uses a small list of tuples with integer keys. It does not measure runtime or cover concurrent mutation; the bisect documentation states that concurrent use or mutation of the same sequence is not thread-safe. [1]

References: [1], [2]

Sources

  1. Python bisect
  2. Python sorting HOWTO