lesson3 practice 1
1. Conceptual — Heapq
Which Python function allows you to efficiently get the 3 largest elements from a list?
A. sort() then slice
B. heapq.nlargest()
C. sorted(reverse=True)
D. Loop through manually
2. Sort Ascending
We have a list of candy counts:
candies = [5, 1, 3, 5, 2, 4, 3, 2]
# Sort candies in ascending order
candies.sort()
Which of the following correctly sorts the list in-place in ascending order?
A. sort()
B. sorted()
C. heapify()
D. nlargest(3, candies)
3. Heapq Top-k
We want the top 3 children with the most candies:
import heapq
candies = [5, 1, 3, 5, 2, 4, 3, 2]
top3 = heapq.nlargest(3, candies)
Which function fills in the blank?
A. nlargest
B. heappop
C. heapify
D. nsmallest
4. Bucket Initialization
We want to count how many children have exactly k candies:
max_candy = 100
counts = [0] * (max_candy + 1)
Which of the following expressions should be used inside the parentheses?
A. max_candy
B. max_candy + 1
C. len(candies)
D. len(candies) + 1
5. Bucket Counting
for c in candies:
counts[c] += 1
Which of the following correctly fills in the index position?
A. c
B. 5
C. counts[c]
D. i
6. Sort Descending
To sort candies in descending order, which code should you use?
candies.sort(reverse=True)
Which of the following correctly fills in the function and keyword argument?
A. candies.sort(descending=True)
B. candies.sort(reverse=True)
C. candies.sorted(reverse=True)
D. candies.heapify(reverse=True)
Comments