Question 1
Back to Exercise
The program below stops with an error. Which statement correctly describes the problem?
def search(a, target):
lo, hi = 0, len(a)
while lo <= hi:
mid = (lo + hi) // 2
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1
print(search([1, 3, 5, 7], 9))
- A It prints -1
- B It loops forever
- C IndexError: with hi = len(a) and lo <= hi, mid can reach len(a) when the target is larger than every item; use hi = len(a) - 1 Correct
- D TypeError
Correct Answer: Option C
Keep the bounds consistent: either hi = len(a) - 1 with lo <= hi, or hi = len(a) with lo < hi.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!