Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get an item from a PriorityQueue without removing it yet?

I want to get the next item in queue but I don't want to dequeue it. Is it possible in Python's queue.PriorityQueue? From the docs, I don't see how can it be done

like image 431
Jiew Meng Avatar asked Feb 15 '12 04:02

Jiew Meng


People also ask

Is PriorityQueue ordered?

A priority queue in Java is a special type of queue wherein all the elements are ordered as per their natural ordering or based on a custom Comparator supplied at the time of creation.

How does a PriorityQueue work?

A priority queue is a special type of queue in which each element is associated with a priority value. And, elements are served on the basis of their priority. That is, higher priority elements are served first. However, if elements with the same priority occur, they are served according to their order in the queue.

Is PriorityQueue LIFO?

PriorityQueue does not care about FIFO / LIFO. it handles priority. in case of several objects with same priority - you can't count on any of FIFO LIFO behavior.

What is PriorityQueue explain with an example?

The priority queue supports only comparable elements, which means that the elements are either arranged in an ascending or descending order. For example, suppose we have some values like 1, 3, 4, 8, 14, 22 inserted in a priority queue with an ordering imposed on the values is from least to the greatest.


2 Answers

If a is a PriorityQueue object, You can use a.queue[0] to get the next item:

from queue import PriorityQueue  a = PriorityQueue()  a.put((10, "a")) a.put((4, "b")) a.put((3,"c"))  print(a.queue[0]) print(a.queue) print(a.get()) print(a.queue) print(a.get()) print(a.queue) 

output is :

(3, 'c') [(3, 'c'), (10, 'a'), (4, 'b')] (3, 'c') [(4, 'b'), (10, 'a')] (4, 'b') [(10, 'a')] 

but be careful about multi thread access.

like image 129
HYRY Avatar answered Sep 21 '22 10:09

HYRY


If you want next element in the PriorityQueue, in the order of the insertion of the elements, use:

for i in range(len(queue.queue)):     print queue.queue[i] 

this will not pop anything out.

If you want it in the priority order, use:

for i in range(len(queue.queue)):     temp = queue.get()     queue.put(temp)     print temp 

If you are using a tuple, instead of a single variable, replace temp by:

((temp1,temp2)) 
like image 40
Victor Juliet Avatar answered Sep 19 '22 10:09

Victor Juliet