Jie*_*eng 2 python queue python-3.x
我有一个ADT(PCB又名过程控制块),我想将它们放入优先级队列.我该怎么做?
我已经使用了如何将项目放入优先级队列?具有次要优先级以确保队列的正确排序.在这里我可以使PCB具有可比性,但在另一个类中,它可能没有意义吗?在那种情况下我可以做什么?
UPDATE
我的代码非常类似于发布的/sf/answers/650283231/
class PCB:
...
# in my class extending `PriorityQueue`
PriorityQueue.put(self, (priority, self.counter, pcb))
Run Code Online (Sandbox Code Playgroud)
我认为问题是pcb在这里仍然没有可比性
好的只是关闭这个问题.继承人我做了什么:
使ADT具有可比性:实施__lt__().
def __lt__(self, other):
selfPriority = (self.priority, self.pid)
otherPriority = (other.priority, other.pid)
return selfPriority < otherPriority
Run Code Online (Sandbox Code Playgroud)
这样,我可以简单地使用 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7327 次 |
| 最近记录: |