Pick the k smallest with heapq
Python's heapq module implements the heap from the previous lesson on plain lists. heapify arranges a list in linear time, and heappop returns the smallest item in logarithmic time.
import heapq
scores = [42, 7, 19, 3]
heapq.heapify(scores)
print(heapq.heappop(scores)) # 3Think before coding
Sorting everything costs n log n even when you need three items. Popping k times from a heap costs n plus k log n. Copy the input first, because heapify rearranges the list it is given. Work through the example by hand before changing the starter. Decide what should happen for an empty input, a single value and a repeated value where those cases apply. The checks use several inputs so a hard-coded answer cannot stand in for the rule.
Your task
Write k_smallest(items, k) returning the k smallest values in ascending order using heapq, without modifying items. If k exceeds the length, return all values sorted.
The explanation opens here once every check passes.