Python and the built-in heap

I am currently trying to write a priority queue in Python using the built-in heapq library. However, I am stuck trying to figure out what Python does with the tiebreak, I want to have a specific condition where I can dictate what happens to the tiebreak, not the heapq library, which seems to be almost something takes out the queue at random. Does anyone know a way to overwrite the disconnect condition or would it be easier to create a priority queue from scratch?

+2


source to share


1 answer


heapq

uses inline comparisons for queue items ( __le__

and friends). A common way around this limitation is the good old approach known as "undecorate" - which is what we did when sorting before the parameter was entered there key=

.

In simple terms, you queue and deactivate not only the items you need (the "payload"), but the items "decorated" with tuples that start with the "keys" you need heapq

to consider. So, for example, it would be okay to insert a tuple like (foo.x, time.time(), foo)

if you want to prioritize using an attribute x

with links split at the time of insertion into the queue - of course when you disable the "undecorate" queue there taking the [-1]

th element of the tuple you get by de-queue.



So, just add the "secondary keys" to account for for the "break" in the decorated tuple you queue AFTER those whose "links" you want to break in this way.

+9


source







All Articles