How to install pqdict
- Download and install ActivePython
- Open Command Prompt
- Type
pypm install pqdict
Lastest release
Implementation of an indexed priority queue written in pure Python. The PQDict class provides the MutableMapping protocol and its instances operate like regular Python dictionaries with a couple extra methods. Think of a Priority Queue Dictionary as a mapping of "dictionary keys" to "priority keys".
What is an "indexed" priority queue?
A priority queue is an abstract data structure that allows you to serve elements in a prioritized fashion. You can insert elements with priorities, and remove or peek at the top priority element. Unlike a standard priority queue, an indexed priority queue additionally allows you to alter the priority of any element in the queue. With the right implementation, each of these operations can be done quite efficiently.
How does it work?
The priority queue is implemented as a binary heap (using a python list), which supports:
- O(1) access to the top priority element
- O(log n) removal of the top priority element
- O(log n) insertion of a new element
In addition, an internal dictionary or "index" maps elements to their position in the heap. This index is synchronized with the heap as the heap is manipulated. As a result, PQDict also supports:
- O(1) lookup of an arbitrary element's priority key
- O(log n) removal of an arbitrary element
- O(log n) updating of an arbitrary element's priority key
Why would I want something like that?
Indexed priority queues can be very useful as schedulers for applications like simulations. They can also be used in efficient implementations of Dijkstra's shortest-path algorithm. Basically, whenever we not only want to be able to quickly find the minimum or maximum element, but we also need to be able to dynamically find and modify the priorities of existing elements in the queue efficiently.
Examples
By default, PQDict uses a min-heap, meaning smaller priority keys have higher priority. Use PQDict.maxpq() to create a max-heap priority queue.
Regular iteration has no prescribed order and is non-destructive.
This also applies to pq.keys(), pq.values(), pq.items() and using iter().
Destructive iteration methods return generators that pop items out of the heap, which amounts to performing a heapsort:
The destructive iterators are pq.iterkeys(), pq.itervalues(), and pq.iteritems().
There is also a convenience function to sort a dictionary-like object by value using a PQDict. It is non-destructive and returns a sorted list of dictionary items.
License
This module was written by Nezar Abdennur and is released under the MIT license. It makes use of some code that was adapted from the Python implementation of the heapq module, which was written by Kevin O'Connor and augmented by Tim Peters and Raymond Hettinger.