14/41
Part 3 of 7 · bisectLearn and do

bisect_left lands before the values equal to x, bisect_right after them

You'll rarely write that loop in Python. The bisect module has it, written in C. Its two searches differ only in what they do with values equal to the one you search for:

from bisect import bisect_left, bisect_right

times = [100, 130, 130, 130, 220, 300]
print(bisect_left(times, 130), bisect_right(times, 130))
print(bisect_left(times, 200), bisect_right(times, 200))
1 4
4 4

Each returns the place where x would go to keep the list sorted, and the answer is how many items sit to its left:

CallReturnsThe place
bisect_left(times, 130)1before every 130
bisect_right(times, 130)4after every 130
bisect_left(times, 200)4between the 130s and 220
bisect_right(times, 200)4the same, since no time is 200

bisect_left is the loop you wrote first. It returns the first index whose value is at least x. Everything before that index is below x, and everything from it on is at least x.

bisect_right returns the first index whose value is greater than x, so it goes past every copy of x. It's the loop from the last_at_or_before checkpoint, before its - 1.

When x isn't in the list, as with 200, the two agree.

Both also take lo and hi, to search only part of the list. bisect_left(a, x, lo, hi) looks only at a[lo:hi], and its answer is still an index into all of a:

print(bisect_left(times, 220, 3, 6))
print(bisect_left(times[3:6], 220))
4
1

The slice answers 1, a place in the copy, and making that copy cost O(n) before the search even started. To search part of a list, don't slice it. Pass lo and hi.

In the editor, write count_equal(times, x): how many changes happened exactly at x. It prints the count at 130 and at 200.