I'm trying to implement the Uniform-cost search in Python and for that, I need a priority queue, which I'm using queue.py from the standard library. However, the end of the algorithm checks if there is any path with a higher cost in the queue. How can I check if there is any given value in my queue if it's not iterable?
We cannot iterate through a priority queue like we can with vectors and other containers. This is why we have used a while loop and various priority_queue methods to print its elements in the program above.
We can iterate on queue using std: :front which will return the front element of the queue and std: :pop which will remove the front element of the queue. But, after iterating on the queue with this method queue will vanish as we are deleting elements of the queue as we iterate over it. Example: C++
util. PriorityQueue implements a binary heap. Unfortunately, there is no easy way to sort a PriorityQueue. If you poll() objects until the queue is empty, the elements will be in the comparator's order.
The simplest queueing discipline is called FIFO, for "first-in-first-out." The most general queueing discipline is priority queueing, in which each customer is assigned a priority, and the customer with the highest priority goes first, regardless of the order of arrival.
queue.PriorityQueue
is actually implemented using a list
, and the put
/get
methods use heapq.heappush
/heapq.heappop
to maintain the priority ordering inside that list
. So, if you wanted to, you could just iterate over the internal list, which is contained in the queue
attribute:
>>> from queue import PriorityQueue
>>> q = PriorityQueue()
>>> q.put((5, "a"))
>>> q.put((3, "b"))
>>> q.put((25, "c"))
>>> q.put((2, "d"))
>>> print(q.queue)
[(2, 'd'), (3, 'b'), (25, 'c'), (5, 'a')]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With