I am using Python's Queue.PriorityQueue
(in an implementation of the A* algorithm, though I'm not sure if this is relevant). I'm using it to hold objects that are non-comparable (an object class provided by a professor that I cannot modify), and Python throws an error when it tries to add an priority-object tuple (ex. pq.put(1, object)
) when it's already holding a tuple with the same priority.
This is the relevant part of the error:
File "pathfinding.py", line 192, in astar
frontier.put((priority, neighbor))
File "/usr/lib/python3.7/queue.py", line 149, in put
self._put(item)
File "/usr/lib/python3.7/queue.py", line 233, in _put
heappush(self.queue, item)
TypeError: '<' not supported between instances of 'InfNode' and 'InfNode'
Basically, I am looking for a way to bypass the PriorityQueue trying to compare these two objects. The exact order in which objects of the same priority are sorted is completely unimportant to me.
I did find this solution, but it doesn't use a PriorityQueue, so I'm not sure if I can do something similar, or if this isn't possible altogether (in which case I'll have to modify my algorithm to be whatever this is, which is not preferable.).
Ok, just in case someone ends up here, I ended up taking superb rain's comment into consideration since I was looking for a simpler solution, and I didn't really have time to overhaul my solution to make it more efficient or better. I just needed something to work.
The solution was basically just implement the suggestion here. If there's anyone that's looking at this that just really doesn't understand how Python works (like me!), stick this at the top.
from dataclasses import dataclass, field
from typing import Any
@dataclass(order=True)
class PrioritizedItem:
priority: int
item: Any=field(compare=False)
And then instead of using .put()
with a tuple, put the entire PrioritizedItem class in instead pq.put(PrioritizedItem(0, start))
or pq.put(PrioritizedItem(priority, data))
. And then to get the item out: current = pq.get().item
.
I would like to acknowledge user2357112-supports-Monica's suggestion to go with a custom heap implementation. If I had time or any real knowledge of how to use Python, I would have liked to have tried it, but again I didn't really have time for more than a bare-minimum-functional solution.
And I'm only posting this here for propriety. This solution may only work starting with Python 3.7.