Predict the output
What does this print?
from bisect import bisect_left, bisect_right
prices = [2, 4, 4, 7, 9]
left4 = bisect_left(prices, 4)
right4 = bisect_right(prices, 4)
print(left4, right4, bisect_left(prices, 10))Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 1 3 5
Right: 4 first appears at 1, the copies end before 3, and 10 would go at the end.
The two bisect functions bracket every copy of a value, which is how counts and ranges are answered in O(log n).
Why not the others?
- B 1 2 5. bisect_right goes past both copies of 4.
- C 2 3 -1. bisect_left returns the first copy, and an insert position is never -1.
Steps come from running the Python solution.
Text version
Target 7:
Cells: [2, 4, 4, 7, 9, 12, 15, 20]
Range: lo up to but not including hi.
- Lo 0, hi 8, mid = 4. a[4] = 9 >= 7: keep the left half
- Lo 0, hi 4, mid = 2. a[2] = 4 < 7: keep the right half
- Lo 3, hi 4, mid = 3. a[3] = 7 >= 7: keep the left half
- Lo 3, hi 3. Answer index = 3. First index with a value >= 7: 3
Result: 3
Target 13:
Cells: [2, 4, 4, 7, 9, 12, 15, 20]
Range: lo up to but not including hi.
- Lo 0, hi 8, mid = 4. a[4] = 9 < 13: keep the right half
- Lo 5, hi 8, mid = 6. a[6] = 15 >= 13: keep the left half
- Lo 5, hi 6, mid = 5. a[5] = 12 < 13: keep the right half
- Lo 6, hi 6. Answer index = 6. First index with a value >= 13: 6
Result: 6