3 of 6
Write a function k_smallest(nums, k) that returns the k smallest elements from a list, in sorted order (smallest first).
Use heapq!
print(k_smallest([5, 3, 8, 1, 4, 2, 7], 3)) # Output: [1, 2, 3] print(k_smallest([10, 20, 30, 40], 2)) # Output: [10, 20] print(k_smallest([7, 7, 7, 1], 1)) # Output: [1]
Check out heapq.nsmallest(k, nums) β it does most of the work!
You can also do it manually:
heapq.heapify()k times with heapq.heappop()import heapq def k_smallest(nums, k): return heapq.nsmallest(k, nums)
import heapq def k_smallest(nums, k): heap = nums[:] # Copy so we don't modify original heapq.heapify(heap) # Turn into a min-heap: O(n) result = [] for _ in range(k): result.append(heapq.heappop(heap)) # Pop smallest each time return result
Why this works: After heapifying, each heappop gives you the next smallest element. Pop k times and you're done!
Now write k_largest(nums, k) that returns the k largest elements in descending order.
print(k_largest([5, 3, 8, 1, 4, 2, 7], 3)) # Output: [8, 7, 5]
Hint: Try heapq.nlargest(), or use the negate trick β push -val to simulate a max-heap!
β Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect
β Functions, classes, recursion, print()
β No file system, subprocess, OS access, or network requests
β No pip install (all supported modules are pre-loaded)
β±οΈ 5 second execution time limit