Issue
I want to add Node objects to Python’s PriorityQueue in Python 2. The Node objects should be prioritized according to the val attribute:
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
I am not allowed to tamper with this ListNode class so I do not have the option to add the __lt__ method to it.
Solution
You should be able to use a tuple to put the priority and the object in the PriorityQueue. Try:
pq = PriorityQueue()
ln2 = ListNode(2)
ln = ListNode(1, ln2)
pq.put((ln.val, ln))
pq.put((ln2.val, ln2))
Answered By – Bret Hogg
This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0