1

I have just started using PriorityQueue module in python from Queue module but i am having a hard time to check if an element exists in the PriorityQueue or not. Below is my Code snippet.

from queue import PriorityQueue
q = PriorityQueue()
q.put(3)
q.put(2)
q.put(1)
ok = 4
if ok in q:
    print("Found")

but i am getting the below error.

TypeError: argument of type 'PriorityQueue' is not iterable

Please tell me how to iterate and check if an element is present in PriorityQueue module in python.

Doubt 2 :- In the above code snippet, PriorityQueue is MIN_HEAP by default, what syntax i should use i want a MAX_HEAP?

1 Answer 1

2

Priority queue is not iterable, so you have to pop out all the elements and then push them back to see if an element is inside. Another option is to use an array to keep track of the elements in the priority queue.

# Assume all the elements are in a range of 0 ~ 999
from queue import PriorityQueue
cnt = [0] * 1000
q = PriorityQueue()
q.put(3)
cnt[3] += 1
q.put(2)
cnt[2] += 1
q.put(1)
cnt[1] += 1
ok = 4
if cnt[ok]:
    print("Found")

For Doubt 2, the simplest way to get max heap is to insert the negative of the element.

max_heap = PriorityQueue()

max_heap.put(-10) // 10
max_heap.put(-20) // 20
max_heap.put(-15) // 15
max_heap.put(-27) // 27

while not max_heap.empty():
    print(-1*max_heap.get())
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer, I have just found out how to search if an element is present (or) not in the PriorityQueue. You can try the below syntax................................ if ok in q.queue: print("ELEMENT FOUND")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.