Heaps and Priority Queues
81 / 170Heaps and Priority QueuesLesson 1 of 8About 43 min
A heap answers one question fast and everything else slowly, which is exactly the trade a lot of problems want.
Type the two lines this prints.
import heapq values = [9, 7, 5, 3, 1]heapq.heapify(values)print(values[0], values[-1])print(sorted(values) == values)k_smallest returns the k smallest values in ascending order. k_largest returns the k largest in descending order, using negation. merge_sorted_lists merges several already-sorted lists into one sorted list using a heap.
Tests
print(k_smallest([5, 1, 8, 3], 2), k_smallest([2], 5))print(k_largest([5, 1, 8, 3], 2), k_largest([], 3))print(merge_sorted_lists([[1, 4, 5], [1, 3, 4], [2, 6]]))print(merge_sorted_lists([]))Output
Run tests to see output.