bisect

bisect does binary search on a list that is already sorted. Each search is O(log n): a million items take about 20 steps.

  • bisect_left(xs, x) gives the first position where x could go, which is the position of the first x if it's there.
  • bisect_right(xs, x) gives the position just after the last x.
  • insort(xs, x) inserts x and keeps the list sorted.

To check membership: i = bisect_left(xs, x), then i < len(xs) and xs[i] == x.

Two catches. The list must be sorted, or the answers are wrong without any error. And insort finds the spot in O(log n) but inserting still shifts items, so it is O(n) overall.

Interviewers like bisect for lookups in ranges, like grade cutoffs, and as a check that you can write binary search yourself. The Algorithms challenges ask you to.

Run it, then add a cutoff for an "S" grade at 100.