我注意到我不能对对象使用PriorityQueue?

2024-05-15 03:53:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个ADT(PCB aka Process Control Block),我想把它们放到一个优先级队列中。我该怎么做?

我已经使用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在这里还是不可比的


Tags: toself队列putblockprocesscontrolclass
1条回答
网友
1楼 · 发布于 2024-05-15 03:53:16

好吧,结束这个问题。以下是我所做的:

使ADT具有可比性:实现__lt__()

def __lt__(self, other):
    selfPriority = (self.priority, self.pid)
    otherPriority = (other.priority, other.pid)
    return selfPriority < otherPriority

这样,我可以简单地使用queue.put(obj)

我发现拉斯曼说得对

"if the priority and counter are always comparable and no two counters ever have the same value, then the entire triple is comparable"

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

相关问题 更多 >

    热门问题