Problem: To implement a queue, it can sort the elements at a given priority and return the highest priority element for each pop operation;
Solution: Implement a simple priority queue with the HEAPQ module
#example.py##Example of a priority queueImportHEAPQclassPriorityqueue:def __init__(self): Self._queue=[] Self._index=0defpush (self, item, priority): Heapq.heappush (Self._queue, (-Priority , Self._index, item)) Self._index+ = 1defpop (self):returnHeapq.heappop (Self._queue) [-1]#Example UseclassItem:def __init__(self, name): Self.name=namedef __repr__(self):return 'Item ({!r})'. Format (self.name) Q=Priorityqueue () Q.push (Item ('Foo'), 1) Q.push (Item ('Bar'), 5) Q.push (Item ('spam'), 4) Q.push (Item ('Grok'), 1)Print("should be bar:", Q.pop ())Print("should be spam:", Q.pop ())Print("should be foo:", Q.pop ())Print("should be grok:", Q.pop ())
Python 3.4.0 (V3.4.0:04f714765c13, Mar, 19:24:06) [MSC v.1600 32bit (Intel)] on Win32type"Copyright","credits" or "license ()" forMore information.>>> ================================ RESTART ================================>>>should be Bar:item ('Bar') should be Spam:item ('spam') should be Foo:item ('Foo') should be Grok:item ('Grok')>>>
You can see that the element returned at the first execution of the pop () operation has the highest priority, and the order of two elements (Foo and gork) of the same priority is returned in the same order as they were inserted into the queue.
In this code, the queue is in the form of tuples (-priority, Self._index, item) , and The priority value is for the queue to be ranked in order from highest to lowest. This is the reverse of the heap default from small to large.
The function of the variable index is to arrange the elements of the same priority in an appropriate order, especially to play an important role in comparing the elements of the same priority.
The Item instance cannot be compared in order:
A=item ('foo') b=item ('bar') Print(", A<b)
>>> Traceback (most recent) :"D:\4autotests\02script\python-cookbook\ python-cookbook-master\src\1\5.implementing_a_priority_queue\example.py" in <module > Print(',a<< Item ()
If you represent elements in the form of tuples (priority, item), you can compare them as long as the precedence is different:
a= (1,item ( " foo ' ') b = (5,item ( " bar )) c = (1,item ( ' , a<c)
>>> a<B: truetraceback (most recent) :"D:\4autotests\ 02script\python-cookbook\python-cookbook-master\src\1\5.implementing_a_priority_queue\example.py" in <module> print(',a<< Item ()
By introducing additional index values to set up tuples (priority, index, item), you can avoid problems where the same precedence cannot be compared, since no two tuples will have the same index value;
A= (1,0,item ('foo'))b= (5,1,item ('bar'))C = (1,2,item ('gork'))print(' ,a<b)print(", A<c)
>>> a<B: Truea<c: True>>>
If you want to use this queue for inter-thread communication, you need to increase the appropriate locking and signaling mechanisms.
"Python Cookbook" "Data Structure and algorithm" 5. Implementing priority queues