iq.lab
Python starts when a code cell comes near or you run one
06 Sorting and binary search

Checkpoint

Sorting and binary search

Eleven items from all four lessons: what a sort costs and what it keeps, the two binary search templates and bisect, searching on the answer, and intervals. Every input is new, and several items hide a classic mistake. Work each one by hand before you check it, the way you would in a round with no run button.

  1. Question 1 of 11.

    Type exactly what this prints. reverse=True sorts from the largest key down.

    scores = [("ana", 2), ("bo", 3), ("cy", 2), ("di", 3), ("ed", 1)]
    for name, points in sorted(scores, key=lambda p: p[1], reverse=True):
        print(name, points)
    
  2. Question 2 of 11.

    This search mixes the two templates. It starts hi at the length, as the first-true template does, but loops while lo <= hi, as the find template does:

    def search(nums, target):
        lo, hi = 0, len(nums)
        while lo <= hi:
            mid = (lo + hi) // 2
            if nums[mid] == target:
                return mid
            if nums[mid] < target:
                lo = mid + 1
            else:
                hi = mid - 1
        return -1

    What does search([1, 3, 5], 9) do?

  3. Question 3 of 11.

    Meetings, in minutes: [[0, 30], [5, 10], [10, 20], [15, 25], [20, 30]]. Each one is [start, end): a room is free the moment its meeting ends. What is the fewest rooms that fit them all?

    rooms

    Type a number: 12, -1, 0.5 and 3/4 all work.

  4. Question 4 of 11.

    Some questions ask for the largest value that still works. Then the answers run yes, then no, so the search finds the first no and steps back one. This function finds the largest whole number x with x * x <= n. Type exactly what it prints.

    def floor_sqrt(n):
        lo, hi = 0, n + 1          # n + 1 surely fails: (n + 1) * (n + 1) > n
        while lo < hi:
            mid = (lo + hi) // 2
            if mid * mid > n:      # does mid fail?
                hi = mid
            else:
                lo = mid + 1
        return lo - 1              # one below the first value that fails
    
    print(floor_sqrt(30), floor_sqrt(36), floor_sqrt(1))
    
  5. Question 5 of 11.

    Insertion sort from this module runs on the nearly sorted list [2, 1, 4, 3, 6, 5]:

    for i in range(1, len(nums)):
        j = i
        while j > 0 and nums[j - 1] > nums[j]:
            nums[j - 1], nums[j] = nums[j], nums[j - 1]
            j -= 1

    Count a comparison every time the while line compares two neighbors. When j is 0, the while line stops without comparing. How many comparisons does the whole sort make?

    comparisons

    Type a number: 12, -1, 0.5 and 3/4 all work.

  6. Question 6 of 11.

    This find-minimum for a rotated sorted list (all values different) asks "is this item smaller than the first item?" instead of comparing with the last item:

    def find_min(nums):
        lo, hi = 0, len(nums) - 1
        while lo < hi:
            mid = (lo + hi) // 2
            if nums[mid] < nums[0]:    # yes: at or after the drop
                hi = mid
            else:
                lo = mid + 1
        return nums[lo]

    On which input does it return the wrong value?

  7. Question 7 of 11.

    Five bookings share one room: [[1, 4], [2, 3], [3, 6], [5, 7], [6, 9]]. A booking may start exactly when another ends. What is the fewest bookings you must remove so that none of the rest clash?

    bookings removed

    Type a number: 12, -1, 0.5 and 3/4 all work.

  8. Question 8 of 11.

    A teammate says: "Merge sort halves the list, like binary search, so it costs O(log n)." Which statement gets merge sort's cost right, for the right reason?

  9. Question 9 of 11.

    Type exactly what this prints. times is sorted.

    from bisect import bisect_left, bisect_right
    
    times = [2, 4, 4, 4, 9, 12]
    print(bisect_left(times, 4), bisect_right(times, 4))
    print(bisect_left(times, 13), bisect_right(times, 1))
    print(bisect_right(times, 9) - bisect_left(times, 3))
    
  10. Question 10 of 11.

    Run the tests before you submit. This question counts as correct if your latest run passes every check.

    Code itThe smallest chunk size

    A load job cuts each batch of rows into chunks of at most d rows. A batch of rows rows needs rows / d chunks, rounded up. Write smallest_chunk(batches, max_chunks), the smallest whole d for which all the batches together need at most max_chunks chunks.

    With batches = [3, 7, 10] and max_chunks = 5: d = 5 needs 1 + 2 + 2 = 5 chunks, and d = 4 needs 1 + 2 + 3 = 6, so the answer is 5. You may assume max_chunks is at least the number of batches, so some d always works.

    The last test is large: trying d = 1, 2, 3, ... in order is too slow.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.
  11. Question 11 of 11.

    Run the tests before you submit. This question counts as correct if your latest run passes every check.

    Code itThe gaps between sessions

    Each item of sessions is [start, end], the minutes one user was active. Sessions come in any order and can overlap. Write free_gaps(sessions), which returns the stretches between the first start and the last end when no session runs, as [start, end] pairs in time order.

    With [[6, 8], [1, 3], [2, 4], [10, 12]] the user is active from 1 to 4, from 6 to 8 and from 10 to 12, so the gaps are [[4, 6], [8, 10]]. Sessions that touch, such as [1, 3] and [3, 5], leave no gap.

    ⌘+Enter runsPython starts when a code cell comes near or you run one
    Write your code where the starter says raise NotImplementedError, then press Run tests. Each check says what it expects.
0 of 11 answered. Unanswered questions count as wrong.