Embercode
✕
Built-in CollectionsQuick quiz

Frequency and top-k with Counter and heapq

8 questions. Covers Top-k with heapq.

Questions 1 to 5 of 8

  1. 1. What does this program print, line by line? ``python from collections import Counter values = [4, 2, 4, 4, 9, 2] counts = Counter(values) print(sorted(counts.items())) print('most frequent:', counts.most_common(1)[0]) print(counts[7]) ``
  2. 2. What does this program print? ``python import heapq def top_k(values, k): if k == 0: return [] heap = [] for v in values: if len(heap) < k: heapq.heappush(heap, v) elif v > heap[0]: heapq.heapreplace(heap, v) return sorted(heap) print(top_k([8, 3, 6, 1, 10, 7], 2)) ``
  3. 3. A top-k function reads n numbers and keeps a min-heap of size k. Which total cost does it take, in Big-O terms?
  4. 4. A generator gives one million numbers, and you want the top 5. What is the most values the heap holds at any one time?
  5. 5. The count_pairs function from the two-sum lesson counts pairs of positions whose values add up to the target. What does it return for 100,000 copies of the value 1 with a target of 2?

5 question(s) left on this page.