Complete the code to create an empty priority queue using Python's heapq module.
import heapq pq = [1]
Priority queues in Python can be implemented using a list with the heapq module. An empty list [] is used to start the queue.
Complete the code to add an element with priority 5 to the priority queue.
import heapq pq = [] heapq.[1](pq, 5)
pop or insert which are not heapq functions for adding elements.The heappush function adds an element to the heap while maintaining the heap property.
Fix the error in the code to remove the smallest element from the priority queue.
import heapq pq = [3, 5, 7] heapq.heapify(pq) smallest = heapq.[1](pq) print(smallest)
pop which removes the last element, not the smallest.The heappop function removes and returns the smallest element from the heap.
Fill both blanks to create a priority queue from a list and then add a new element 2.
import heapq pq = [4, 1, 7] heapq.[1](pq) heapq.[2](pq, 2)
sorted instead of heapify to create a heap.heapify converts a list into a heap in-place. Then heappush adds a new element while keeping the heap property.
Fill all three blanks to pop the smallest element, then push 6, and finally peek at the smallest element without removing it.
import heapq pq = [3, 8, 5] heapq.heapify(pq) smallest = heapq.[1](pq) heapq.[2](pq, 6) peek = pq[3]
pop() which removes elements.heappop removes the smallest element, heappush adds a new element, and accessing pq[0] peeks at the smallest element without removing it.