Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I notice I cannot use PriorityQueue for Objects?

I have an ADT (PCB aka Process Control Block), I want to put them into a priority queue. How can I do it?

I already used How to put items into priority queues? to have a secondary priority to ensure the correct ordering of the queue. Here I can make the PCB comparable, but in another class, it may not make sense? In that case what might I do?

UPDATE

My code is very similar to that posted https://stackoverflow.com/a/9289760/292291

class PCB:
    ...

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

I think the problem is pcb is still not comparable here

like image 697
Jiew Meng Avatar asked Dec 27 '22 06:12

Jiew Meng


1 Answers

OK just to close off this question. Heres what I did:

Make the ADT comparable: Implement __lt__().

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

This way, I can simply use queue.put(obj)

I found that @larsmans is right in saying

"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
like image 180
Jiew Meng Avatar answered Dec 31 '22 13:12

Jiew Meng