[ 187 ] A priority queue might be used, for example, by a search engine to ensure it refreshes
the content of the most popular web pages before crawling sites that are less likely to
be searched for. A product recommendation tool might use one to display information
about the most highly ranked products while still loading data for the lower ranks.
Note that a priority queue will always return the most important element currently
in the queue. The
get()
method will block (by default) if the queue is empty, but it
will not block and wait for a higher priority element to be added if there is already
something in the queue. The queue knows nothing about elements that have not
been added yet (or even about elements that have been previously extracted), and
only makes decisions based on the current contents of the queue.
This interactive session shows a priority queue in action, using tuples as weights to
determine what order items are processed in:
>>> heap.put((3, "three")) >>> heap.put((4, "four")) >>> heap.put((1, "one") ) >>> heap.put((2, "two")) >>> heap.put((5, "five"), block=False) Traceback (most recent call last): File "", line 1, in heap.put((5, "five"), block=False) File "/usr/lib64/python3.3/queue.py", line 133, in put raise Full Full >>> while not heap.empty(): print(heap.get()) (1, 'one') (2, 'two') (3, 'three') (4, 'four') Priority queues are almost universally implemented using the
heap
data structure.
Python's implementation utilizes the
heapq
module to effectively store a heap inside
a normal list. I direct you to an algorithm and data-structure's textbook for more
information on heaps, not to mention many other fascinating structures we haven't
covered here. No matter what the data structure, you can use object-oriented principles
to wrap relevant algorithms (behaviors), such as those supplied in the
heapq
module,
around the data they are structuring in the computer's memory, just as the
queue
module has done on our behalf in the standard library.
www.it-ebooks.info