Priority_queue module
The priority queue defined by this module uses
heapq
the module internally, so its time complexity is the same as that of heapq.When all elements of an object are comparable, by default they are sorted according to the first element of the object in the queue, and the smaller the priority, the higher the priority. When the first elements are the same, the sizes of the subsequent elements are compared in turn for sorting.
Because
PriorityQueue
it is inherited fromQueue
the class, the usage of many functions can directly refer toQueue
the functions in the class.from queue import PriorityQueue as PQ pq = PQ() pq.put((1, 'a')) pq.put((2, 'c')) pq.put((2, 'b')) pq.put((2, 'b')) print(pq.queue) # [(1, 'a'), (2, 'b'), (2, 'b'), (2, 'c')] item0 = pq.get() # (1, 'a') print(pq.queue) # [(2, 'b'), (2, 'b'), (2, 'c')] print(pq.qsize()) # 优先队列的尺寸 while not pq.empty(): print(pq.get())
For custom classes using the priority queue , it needs to be compared according to a certain attribute of the class when entering the queue.
Method: Use the overloaded method __lt__, __lt__ is a method in python for specific comparisons.
import queue class person(object): def __init__(self,name,score): self.name = name self.score = score def __lt__(self, other): return self.score > other.score p1 = person("张三",15) p2 = person("李四",23) p3 = person("王五",12) p4 = person("朱五",32) que = queue.PriorityQueue() que.put(p1) que.put(p2) que.put(p4) que.put(p3) print(que.get().name) print(que.get().name) print(que.get().name) print(que.get().name)
Among them, __lt__ defines the arrangement from large to small according to the score attribute. That is, when PriorityQueue enqueues a class instance, it will automatically compare according to the score attribute.
Here is an example
We need to sort the mice by weight from largest to smallest, and then output their hat colors.
class Node :
def __init__(self, w, col) :
self.w = w
self.col = col
def __lt__(self, other) :
return self.w > other.w # 按w从大到小排序
N = int(input())
lst = []
for i in range(N) :
w, col = input().split()
lst.append(Node(int(w), col))
lst.sort() # 排序
for i in range(N) :
print(lst[i].col)
Writing using priority queue
from queue import PriorityQueue
class Node :
def __init__(self, w, col) :
self.w = w
self.col = col
def __lt__(self, other) :
return self.w > other.w
q = PriorityQueue()
n = int(input())
for i in range(n) :
w, col = input().split()
w = int(w)
q.put(Node(w, col))
while q.qsize() :
print(q.get().col)