iq.lab
Python starts when a code cell comes near or you run one
09 Heaps and tries

Checkpoint

Heaps and tries

Twelve items from all three lessons: how a heap works, top k and merging, and tries. Every input is new, so work each one on paper first: write the heap as a list with its indexes under it, and draw the trie as a tree of letters. The classic slips are here on purpose: a heap read as if it were sorted, a heap that keeps the wrong end, a tie that reaches two dicts, a node taken for a stored word. The last two items are code: a small heap that sorts a nearly sorted list, and a trie that counts searches by prefix.

  1. Question 1 of 12.

    Five numbers go into an empty heap with heappush. Type exactly what this prints. max scans the whole list.

    import heapq
    
    heap = []
    for x in [6, 4, 9, 2, 7]:
        heapq.heappush(heap, x)
    print(heap)
    print(heap[0], heap[-1], max(heap))
    
  2. Question 2 of 12.

    A min-heap holds 20 items, at indexes 0 to 19. You push one more. At most how many swaps can that push make? Type a whole number.

    swaps at most

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

  3. Question 3 of 12.

    A teammate wants the 2 largest numbers. Reasoning "largest means max-heap", they push every number negated. Type exactly what this prints.

    import heapq
    
    heap = []
    for x in [5, 1, 8, 3, 9, 2]:
        heapq.heappush(heap, -x)
        if len(heap) > 2:
            heapq.heappop(heap)
    print(sorted(-v for v in heap))
    
  4. Question 4 of 12.

    Insert "tea", "ten", "to", "inn" and "in" into an empty trie, in that order. How many letter nodes does the trie have? Do not count the root. Type a whole number.

    letter nodes

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

  5. Question 5 of 12.

    Each job is a dict, and the heap orders jobs by a priority number. What does this program do?

    import heapq
    
    jobs = []
    heapq.heappush(jobs, (2, {"name": "load"}))
    heapq.heappush(jobs, (2, {"name": "report"}))
    print(jobs[0][1]["name"])
  6. Question 6 of 12.

    nums holds n = 1,000,000 numbers, already in memory. Which of these return the 10 largest numbers and cost less than O(n log n) in the worst case? Choose every one that does.

    Choose every option that applies.

  7. Question 7 of 12.

    This builds a dict-of-dicts trie, then follows three texts. Each line prints the text, whether its node exists, and whether a stored word ends there. Type exactly what it prints.

    root = {}
    for word in ["band", "ban", "bat"]:
        node = root
        for ch in word:
            node = node.setdefault(ch, {})
        node["$"] = True
    
    def follow(text):
        node = root
        for ch in text:
            if ch not in node:
                return None
            node = node[ch]
        return node
    
    for text in ["ba", "ban", "bands"]:
        node = follow(text)
        print(text, node is not None, node is not None and "$" in node)
    
  8. Question 8 of 12.

    This merge stops after taking 4 values. Each taken value is recorded with the number of the list it came from. Type exactly what it prints.

    import heapq
    
    lists = [[2, 6], [1, 7, 8], [3]]
    heap = [(values[0], i, 0) for i, values in enumerate(lists)]
    heapq.heapify(heap)
    taken = []
    while len(taken) < 4:
        value, i, j = heapq.heappop(heap)
        taken.append((value, i))
        if j + 1 < len(lists[i]):
            heapq.heappush(heap, (lists[i][j + 1], i, j + 1))
    print(taken)
    print(len(heap))
    
  9. Question 9 of 12.

    A dict-of-dicts trie holds "cab", "cot" and "dog", inserted in that order. You run matches(root, "..g", 0) with the function from the tries lesson: a letter follows its one child, and a dot tries every child in the order they were added and returns True at the first match. How many calls to matches run in all, counting the first one? Type a whole number.

    calls to matches

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

  10. Question 10 of 12.

    This is the two-heap running median from the top-k lesson, on five numbers. Type exactly what it prints.

    import heapq
    
    low, high = [], []
    for num in [8, 2, 6, 10, 4]:
        heapq.heappush(low, -num)
        heapq.heappush(high, -heapq.heappop(low))
        if len(high) > len(low):
            heapq.heappush(low, -heapq.heappop(high))
    print(sorted(-v for v in low), sorted(high))
    print(-low[0], high[0])
    
  11. Question 11 of 12.

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

    Code itSort a nearly sorted list

    A log of numbers arrives almost in order: every number is at most k positions away from its place in sorted order. In [3, 1, 2, 6, 4, 5] with k = 2, the 3 sits at index 0 but belongs at index 2, two positions away, and no number is farther from its place than that.

    Write sort_nearly_sorted(nums, k), which returns a new sorted list and leaves nums unchanged. Sorting from scratch costs O(n log n). Use a min-heap that never holds more than k + 1 numbers, for O(n log k). The tests include 50,000 numbers, where scanning every number left for each next answer runs out of time.

    ⌘+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.
  12. Question 12 of 12.

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

    Code itCount searches by prefix

    A search box logs every search. Write a class PrefixCounter with two methods:

    • add(query) records one search for query. The same query can be recorded many times, and each one counts.
    • count_prefix(prefix) returns how many recorded searches start with prefix. A search starts with itself, and the empty prefix "" starts every search.

    After recording cat, car, cart, dog and car, count_prefix("ca") is 4 and count_prefix("car") is 3. Each call must take time that depends only on the length of its text, not on how many searches are recorded. The tests include 15,000 searches and 15,000 counts, where checking every recorded search for every count runs out of time.

    ⌘+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 12 answered. Unanswered questions count as wrong.