![]() You could easily wrap this behavior in a small function so that you repeat yourself less. If you want to preserve insert order in case of duplicates, you can do this: from queue import PriorityQueueĪnd proceed similarly with heapq. In that case, it depends how you want to deal with duplicate values. If you have duplicate values, then the comparison will look at the second element of the tuple, and will break because your Nodes are not comparable. With queue.PriorityQueue, use tuples as suggested by the doc from queue import PriorityQueue P.queue # Īnother way, if you can specify the priority of each element as you push it in. Then just add them normally: p = PriorityQueue() Or if you want to just pass Node objects that exist already: ComparableNode: So you can wrap it in a class that you create. Let's assume you have this setup: class Node:īut you can't modify Node. One solution, without passing a comparator, is to wrap your Node objects in another object, say ComparableNode, which implements the comparisons you would like on the Node object. Note that methods of asyncio queues don’t have a timeout parameter use asyncio.waitfor () function to do queue operations with a timeout. Although asyncio queues are not thread-safe, they are designed to be used specifically in async/await code. I understand that the cause of this error is that the Node objects need to be comparable to one another, and the way to achieve this according to the documentation is to at least implement lt and eq methods for Node.īut for my problem, since I wont be able to modify the Node class, will I be able to pass a way( a lambda or a Comparator) to the PriorityQueue to help it determine the ordering.(I am expecting something Java like)Īny alternative to achieve this is also appreciated.(remember Node is not modifiable) asyncio queues are designed to be similar to classes of the queue module. Q.put((b.val, b)) // Errors TypeError: '<' not supported between instances of 'Node' and 'Node' ![]() Q.put(b) // Errors TypeError: '<' not supported between instances of 'Node' and 'Node' It still compares the 'node' object to resolve the ties. ![]() It still gives me "TypeError: '<' not supported between instances of 'Node' and 'Node'". I tried adding them as tuples(node.val, node) to the queue. I need these objects prioritized based on a field of the object. I want to use a PriorityQueue to which I need to add objects of a class (say Node) which I cannot modify. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |