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

To implement “decrease-key” effectively, you’d need to access the functionality “decrement this element AND swap this element with a child until heap condition is restore”. In heapq.py, that’s called _siftdown (and similarly _siftup for INcrementing). So the good news is that the functions are there… the bad news is that their names start with an … Read more

When should I use make_heap vs. Priority Queue?

There’s no difference in terms of performance. std::priority_queue is just an adapter class that wraps the container and the very same heap-related function calls into a class. The specification of the std::priority_queue openly states that. By building a heap from an exposed std::vector and calling heap-related functions directly, you keep it open to the possibility … Read more

How do I find the median of numbers in linear time using heaps?

You would use a min-max-median heap to find the min, max and median in constant time (and take linear time to build the heap). You can use order-statistics trees to find the kth smallest/largest value. Both of these data structures are described in this paper on min-max heaps [PDF]. Min-max heaps are binary heaps that … Read more

What’s the relationship between “a” heap and “the” heap?

Nothing much, to be honest. I would imagine that the word heap was simply taken with it’s everday (non-technical) usage and applied to these two concepts individually as reasonably good analogies. In the first case (tree data structure meaning), the description heap is most appropiate because “greater” objects are placed higher up in the tree … Read more

How to implement O(logn) decrease-key operation for min-heap based Priority Queue?

You can do following: store a hashmap inside your heap that maps your heap values to heap indexes. Then you should extend your usual heap-logic just a bit: on Swap(i, j): map[value[i]] = j; map[value[j]] = i; on Insert(key, value): map.Add(value, heapSize) in the beginning; on ExtractMin: map.Remove(extractedValue) in the end; on UpdateKey(value, newKey): index … 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

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)