Predict the output
This version has a bug. What does it print?
def find_last_small(vals: list[int], x: int) -> int:
lo, hi, steps = 0, len(vals) - 1, 0
while lo < hi and steps < 10:
steps += 1
mid = (lo + hi) // 2
if vals[mid] <= x:
lo = mid
else:
hi = mid - 1
return steps
print(find_last_small([1, 2], 5))Choose an answer, then open Show answer below to check it.
Show answer
Answer: A 10
Right: with lo = mid and mid rounding down, a two-item range never shrinks; only the step cap stops it.
When one branch sets lo = mid, the middle must round up, or the search stalls on two items.
Why not the others?
- B 1. lo stays at 0 because mid = 0 every time.
- C 2. The range [0, 1] keeps producing mid = 0, so progress never happens.