Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over a Priority Queue?

Tags:

python

search

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?

like image 755
Rodrigo Souza Avatar asked Sep 13 '14 13:09

Rodrigo Souza


People also ask

Can we iterate over priority queue C++?

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.

Can you iterate over queue?

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++

Can you sort a priority queue in Java?

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.

Is priority queue FIFO or LIFO?

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.


1 Answers

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')]
like image 127
dano Avatar answered Oct 09 '22 04:10

dano