Question presented to candidate:
"Say you have a big sorted list and you need to find where a value belongs, or count how many values fall in a range. What does Python's bisect module do, how does it work, and when is it the wrong tool?"
What a strong answer should cover:
bisectis binary search on an already sorted sequence: it halves a[lo, hi)window each step, so it needs about log2(n) comparisons (20 for a million items).bisect_leftreturns the first position wherexcould go (before equal items),bisect_right/bisectthe position after equal items;right - leftcounts the copies ofx.insort/insort_left/insort_rightkeep a list sorted, but the search is O(log n) while the list insert is O(n), so it does not beat a heap or a sorted container for many inserts.- The
key=argument (added in Python 3.10) is applied to the list items, not tox;loandhilimit the window; only<is used for comparisons. - Typical uses: membership in a sorted list, range counts, bucketing a score into a grade, and keeping a small sorted list up to date.
Code / implementation expected: Yes β either use bisect for a lookup/range task, or write bisect_left by hand.