ealeon
ealeon

Reputation: 12460

Python priority queue pops in descending order

from queue import PriorityQueue

q = PriorityQueue()

q.put((2, 'code'))
q.put((1, 'eat'))
q.put((3, 'sleep'))

while not q.empty():
    next_item = q.get()
    print(next_item)

# Result:
#   (1, 'eat')
#   (2, 'code')
#   (3, 'sleep')

What can i do so that it will pop in a reverse order? ie descending

Upvotes: 5

Views: 7308

Answers (3)

Thomas Blankenhorn
Thomas Blankenhorn

Reputation: 256

There is no way to change the behavior of the queue class. I would decorate the items before queuing them, and un-decorate them after retrieving them, something like this:

def decorated(item):
    return (-item[0],) + item

def undecorated(item):
    return item[1:]

That gives you items that will queue up in the right order:

>>> decorated(1, 'eat')
(-1, 1, 'eat')
>>> undecorated(-1, 1, 'eat')
(1, 'eat')

That way you can say q.put(decorated(item)) instead of q.put(item). Analogously, you retrieve the item by saying undecorated(q.get()) instead of q.get(). After this, the rest of your code keeps working as it did before.

Upvotes: 1

Ghassen
Ghassen

Reputation: 794

you can use this method as a trick multiply by -1 to inverse the order :

q = PriorityQueue()

q.put((2*(-1), 'code'))
q.put((1*(-1), 'eat'))
q.put((3*(-1), 'sleep'))
while not q.empty():
    next_item = q.get()
    print(next_item)

output:

(-3, 'sleep')
(-2, 'code')
(-1, 'eat')

Upvotes: 11

JacobIRR
JacobIRR

Reputation: 8966

The PriorityQueue API let's you define the order.

If you want those strings in the opposite order, just reverse the int values in the tuples:

from queue import PriorityQueue

q = PriorityQueue()

q.put((2, 'code'))
q.put((3, 'eat'))
q.put((1, 'sleep'))

while not q.empty():
    next_item = q.get()
    print(next_item)

#(1, 'sleep')
#(2, 'code')
#(3, 'eat')

There is no way to invert the behavior of the PriorityQueue and python's (non-threadsafe) heapq uses the same ordering. But I see your point, the real name should probably be "MinPriorityQueue" since 1 is always first in this structure.

Upvotes: 0

Related Questions