heap

Get list of elements currently in heap using heapq in Python?

Get list of elements currently in heap using heapq in Python? Question: This structure i have built for easier understanding and usability class PriorityQueue: """ Implements a priority queue data structure. """ def __init__(self): self.heap = [] self.count = 0 def push(self, item, priority): entry = (priority, self.count, item) heapq.heappush(self.heap, entry) self.count += 1 def …

Total answers: 1

Understanding how to create a heap in Python

Understanding how to create a heap in Python Question: The collections.Count.most_common function in Python uses the heapq module to return the count of the most common word in a file, for instance. I have traced through the heapq.py file, but I’m having a bit of trouble understanding how a heap is created/updated with respect to …

Total answers: 4

Python: delete element from heap

Python: delete element from heap Question: Python has heapq module which implements heap data structure and it supports some basic operations (push, pop). How to remove i-th element from the heap in O(log n)? Is it even possible with heapq or do I have to use another module? Note, there is an example at the …

Total answers: 2

How to implement Priority Queues in Python?

How to implement Priority Queues in Python? Question: Sorry for such a silly question but Python docs are confusing… Link 1: Queue Implementation http://docs.python.org/library/queue.html It says that Queue has a class for the priority queue. But I could not find how to implement it. class Queue.PriorityQueue(maxsize=0) Link 2: Heap Implementation http://docs.python.org/library/heapq.html Here they say that …

Total answers: 3

How to make heapq evaluate the heap off of a specific attribute?

How to make heapq evaluate the heap off of a specific attribute? Question: I wish to hold a heap of objects, not just numbers. They will have an integer attribute in them that the heap can sort by. The easiest way to use heaps in python is heapq, but how do I tell it to …

Total answers: 9

Peeking in a heap in python

Peeking in a heap in python Question: What is the official way of peeking in a python heap as created by the heapq libs? Right now I have def heappeak(heap): smallest = heappop(heap) heappush(heap, smallest) return smallest which is arguably, not very nice. Can I always assume that heap[0] is the top of the heap …

Total answers: 2

How can I implement decrease-key functionality in Python's heapq?

How can I implement decrease-key functionality in Python's heapq? Question: I know it is possible to realize decrease-key functionality in O(log n) but I don’t know how? Asked By: zerodx || Source Answers: To implement “decrease-key” effectively, you’d need to access the functionality “decrement this element AND swap this element with a child until heap …

Total answers: 7