I am working on a simulation experiment and trying to make my code as efficient as possible. In one part, I have a min heap priority queue that I have implemented using heapq
module.
Throughout the simulation, I have to pop all elements with the smallest key. The straightforward approach to do this would be:
elements = []
k1, v1 = heapq.heappop(heap)
elements.append((k1,v1))
k2, v2 = heap[0] #looks at the smallest item without popping
while(k1 == k2):
k1, v1 = heapq.heappop(heap)
elements.append((k1,v1))
k2, v2 = heap[0]
return elements