Embercode
✕
Divide and ConquerQuick quiz

Binary search in Python

8 questions. Covers Binary search on the answer in Python.

Questions 1 to 5 of 8

  1. 1. What does this code print? ``python a = [2, 4, 4, 4, 7, 9, 12] lo = 0 hi = len(a) while lo < hi: mid = lo + (hi - lo) // 2 if a[mid] >= 9: hi = mid else: lo = mid + 1 print(lo) ``
  2. 2. What does this code print? ``python lo = 1_500_000_000 hi = 2_000_000_000 print((lo + hi) / 2) ``
  3. 3. This find_exact function loops forever on [1, 5] with target 9. What is the bug? ``python def find_exact(a: list[int], target: int) -> int: lo = 0 hi = len(a) - 1 while lo <= hi: mid = lo + (hi - lo) // 2 if a[mid] == target: return mid if a[mid] < target: lo = mid else: hi = mid - 1 return -1 ``
  4. 4. This least_feasible is called as least_feasible(0, len(a), lambda i: a[i] >= 4) on a = [2, 4, 4, 4, 7, 9, 12]. It returns 0, but the first yes is at index 1. What is the bug? ``python def least_feasible(lo: int, hi: int, ok: Callable[[int], bool]) -> int: while lo < hi: mid = lo + (hi - lo) // 2 if ok(mid): hi = mid - 1 else: lo = mid + 1 return lo ``
  5. 5. Write the Python expression for the middle index that starts at lo and adds half the distance from lo to hi, using floor division. Write only the expression, without mid =.

    Type your answer.

5 question(s) left on this page.

Typed answers ignore extra spaces and, for most questions, capital letters.