Search code examples
pythonfindpriority-queue

Python, find element in PriorityQueue by value


The priority queue PQ stores pairs

(weight, element),

sorted according to the weight. Does Python's implementation support the search operation in PQ by the element value (element in PQ or not)?

PQ = queue.PriorityQueue()
PQ.put((1,2))
PQ.put((5,6))
val = 6
print (val in PQ.queue)       #Nothing has been found

I suppose that items in PQ are stored in PQ.queue as tupples.

Thanks for your help.


Solution

  • Try this,

    If you want to search for an element:

    import queue
    
    PQ = queue.PriorityQueue()
    PQ.put((1, 2))
    PQ.put((5, 6))
    val =  4
    
    while not PQ.empty():
       if val in PQ.get():
         print(True)
    

    If you want to search for a tuple:

    import queue
    
    PQ = queue.PriorityQueue()
    PQ.put((1, 2))
    PQ.put((5, 6))
    val = (5, 6)
    
    while not PQ.empty():
      if val == PQ.get():
         print(True)