Read an insertion point as a count, and most lookups take one line
The name says where you'd insert x. Read it instead as a count. The table uses a half-open range, written [start, end): it includes its start and leaves out its end. That's the usual way to state a time range. [start, end] includes both ends. Its last column runs each line on a = [100, 130, 130, 130, 220, 300], with x = 130, a range from 130 to 300, and 200 for the last row.
| Question | Expression | Result |
|---|---|---|
| How many are less than x | bisect_left(a, x) | 1 |
| How many are at most x | bisect_right(a, x) | 4 |
| The latest at or before x | a[bisect_right(a, x) - 1] | 130, index 3 |
| The latest strictly before x | a[bisect_left(a, x) - 1] | 100, index 0 |
| The earliest at or after x | a[bisect_left(a, x)] | 130, index 1 |
How many in [start, end) | bisect_left(a, end) - bisect_left(a, start) | 4 |
How many in [start, end] | bisect_right(a, end) - bisect_left(a, start) | 5 |
| Is x there | i = bisect_left(a, x), then i < len(a) and a[i] == x | False |
Pick the pair by asking what a value equal to an end should do. The half-open range uses bisect_left at both ends:
| Range | Bounds | Count |
|---|---|---|
[130, 300): 130 counts, 300 doesn't | bisect_left at both ends: 1 and 5 | 5 - 1 = 4 |
[130, 300]: both ends count | bisect_right at the end: 1 and 6 | 6 - 1 = 5 |
The three lookups that index into the list need an edge check every time: the index must be at least 0 and below len(a). Subtracting 1 can give -1, and the earliest at or after can be len(a), one past the last index.
In the editor, write changes_between(times, start, end), a count over a half-open range. It prints the changes from 130 up to 200, and a range that ends before it starts.