You can use Queue.PriorityQueue.
Recall that Python isn't strongly typed, so you can save anything you like: just make a tuple of (priority, thing) and you're set.
You can use Queue.PriorityQueue.
Recall that Python isn't strongly typed, so you can save anything you like: just make a tuple of (priority, thing) and you're set.
When using a priority queue, decrease-key is a must-have operation for many algorithms (Dijkstra's Algorithm, A*, OPTICS), I wonder why Python's built-in priority queue does not support it. None of the other answers supply a solution that supports this functionality.
A priority queue which also supports decrease-key operation is this implementation by Daniel Stutzbach worked perfectly for me with Python 3.5.
from heapdict import heapdict
hd = heapdict()
hd["two"] = 2
hd["one"] = 1
obj = hd.popitem()
print("object:",obj[0])
print("priority:",obj[1])
# object: one
# priority: 1
A priority queue is not supposed to be sorted. The priority queue only guarantees that when you call get(), it returns you the highest priority item.
Internally, queue.PriorityQueue uses a binary heap to contain the items.
The reason it doesn't use a sorted array is because maintaining a sorted array is expensive. Adding and removing items would be O(n) operations. A binary heap makes those O(log n) operations.
See https://github.com/python/cpython/blob/2.7/Lib/Queue.py and https://docs.python.org/2/library/heapq.html for details.
It is in order, but the order of heap. PriorityQueue is implemented by heap.
The q.queue is just a simple list, but every time you insert an element, it will do heap shift.
There is a visualization website which you can test. And you will see when you insert (3, '3'), it is smaller than its parent node (4, 'last'), so they will be exchanged.
I know python has heapq and queue.priorityqueue but honestly, both of them are really cumbersome compared to Java's priorityqueue. I find it tedious to have to insert a tuple, with the first element in the tuple defining the priority. Also, it makes it hard to write more complex comparisons. Is there a way we can pass in a comparator to the Priorityqueue? I know it's possible to define classes with their own comparator method, but again, this is really tedious and I'm looking for something as close as possible to Java's PQ.