Creating a python priority Queue

て烟熏妆下的殇ゞ 提交于 2019-12-02 11:40:19

Use the heapq module in the standard library.

You don't specify how you wanted to associate priorities with dictionaries, but here's a simple implementation:

import heapq

class MyPriQueue(object):
    def __init__(self):
        self.heap = []

    def add(self, d, pri):
        heapq.heappush(self.heap, (pri, d))

    def get(self):
        pri, d = heapq.heappop(self.heap)
        return d

This is what I usually present as a side note in some of my patterns talks:

class PriorityQueue(object):
 def __init__(self, key=lambda x: x):
   self.l = []
   self.key = key
 def __len__(self):
   return len(self.l)
 def push(self, obj):
   heapq.heappush(self.l, (self.key(obj), obj))
 def pop(self):
   return heapq.heappop(self.l)[-1]

The OP's requirements are apparently to use operator.itemgetter('priority') as the key argument when instantiating PriorityQueue (needs an import operator at top of module, of course;-).

You can do this by adding a dict object to the class, and search it inside.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!