我有一个ADT(PCB又称过程控制块),我想将它们放入优先级队列。我该怎么做?
我已经使用How to put items into priority queues?来获得次要优先级,以确保队列的正确排序。在这里我可以使PCB具有可比性,但在另一个类中,它可能没有意义吗?在那种情况下我可以做什么?
更新
我的代码与发布的https://stackoverflow.com/a/9289760/292291
非常相似class PCB:
...
# in my class extending `PriorityQueue`
PriorityQueue.put(self, (priority, self.counter, pcb))
我认为问题是pcb在这里仍然没有可比性
答案 0 :(得分:6)
好的就是关闭这个问题。继承人我做了什么:
使ADT具有可比性:实施__lt__()
。
def __lt__(self, other):
selfPriority = (self.priority, self.pid)
otherPriority = (other.priority, other.pid)
return selfPriority < otherPriority
这样,我可以简单地使用queue.put(obj)
我发现@larsmans说的是正确的
“如果优先级和计数器始终具有可比性且没有两个计数器具有相同的值,则整个三元组具有可比性”
jiewmeng@JM:~$ python3.2
Python 3.2.2 (default, Sep 5 2011, 21:17:14)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> class Test:
... def __init__(self, name):
... self.name = name
...
>>> from queue import PriorityQueue
>>> q = PriorityQueue()
# duplicate priorities triggering unorderable error
>>> q.put((2, Test("test1")))
>>> q.put((1, Test("test1")))
>>> q.put((3, Test("test1")))
>>> q.put((3, Test("test1")))
>>> q.put((3, Test("test2")))
>>> while not q.empty():
... print(q.get().name)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/lib/python3.2/queue.py", line 195, in get
item = self._get()
File "/usr/lib/python3.2/queue.py", line 245, in _get
return heappop(self.queue)
TypeError: unorderable types: Test() < Test()
# unique priority fields thus avoiding the problem
>>> q = PriorityQueue()
>>> q.put((3, Test("test1")))
>>> q.put((5, Test("test5")))
>>> while not q.empty():
... print(q.get()[1].name)
...
test1
test5