2012-02-15 15 views
2

私はADT(PCB別名プロセスコントロールブロック)を持っています。それらを優先キューに入れたいと思います。どうしたらいいですか?オブジェクトにPriorityQueueを使用することはできません。

私はすでにHow to put items into priority queues?を使用して、キューの正しい順序付けを保証するために第2優先順位を持っています。ここではPCBを同等にすることができますが、別のクラスでは意味をなさないかもしれません。その場合はどうしたらいいですか?

UPDATE

私のコード私はこの問題は、PCBと思いhttps://stackoverflow.com/a/9289760/292291

class PCB: 
    ... 

# in my class extending `PriorityQueue` 
PriorityQueue.put(self, (priority, self.counter, pcb)) 

を投稿することが非常に似てまだここに比較することはできません

+0

オブジェクトを優先度と比較できない場合は、 '(priority、obj)'のペアをPQに挿入します。 –

+0

@larsmans、コードからhttp://stackoverflow.com/a/9289760/292291、 'PriorityQueue.put(self、(priority、self.counter、item))'すでに同様のことをしました –

+1

@JiewMeng:if優先度とカウンタは常に比較可能であり、2つのカウンタの値が同じではない場合、トリプル全体が同等です。 –

答えて

6

OKちょうどこの質問を閉鎖します。私が何をしたのか:

ADTを匹敵させる:__lt__()を実装してください。

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

この方法で、私は単にqueue.put(obj)

を使用することができ、私は優先順位とカウンタは、常に比較され、どの2つのカウンターが今まで持っていない場合@larsmansは

を言うに右であることがわかりました同じ値であれば、トリプル全体が同等です "

[email protected]:~$ 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 
関連する問題