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

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 …

Read more

Peeking in a heap in python

Yes, you can make this assumption, because it is stated in the documentation: Heaps are arrays for which heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2] for all k, counting elements from zero. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that heap[0] is always …

Read more

How to look ahead one element (peek) in a Python generator?

For sake of completeness, the more-itertools package (which should probably be part of any Python programmer’s toolbox) includes a peekable wrapper that implements this behavior. As the code example in the documentation shows: >>> p = peekable([‘a’, ‘b’]) >>> p.peek() ‘a’ >>> next(p) ‘a’ However, it’s often possible to rewrite code that would use this …

Read more