I have an algorithm that creates two heaps, minHeap and maxHeap. The only difference between the two is that maxHeap reverses the sign of minHeap, a simple hack to use Python’s heapq data structure as a max heap. Here’s my code for creating the heaps (the heap key is basically the number of workers in a dictionary for a given day of the week):
for day in self.weekDict:
if day != 'Saturday' and len(self.weekDict[day]) != 0: #saturdays and holidays not part of optimization
heapq.heappush(minHeap, (len(self.weekDict[day]), day))
heapq.heappush(maxHeap, (-len(self.weekDict[day]), day))
The minHeap works just as expected, but the max heap gives me odd behavior when there are more than one of the same key. See below:
[(-8, 'Thursday'), (-7, 'Monday'), (-5, 'Friday'), (-7, 'Wednesday'), (-7, 'Tuesday')]
Why are the last two days out of order? Is it because only the first day is guaranteed to be the minimum, and once I pop the first day off the heap will automatically adjust itself?
A heap is not a sorted list. A heap is a binary tree which happens to be stored as a list. The elements of a heap have the following property:
a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for all k in a
See the docs for a fuller explanation and a nice picture to help follow the structure: http://docs.python.org/2/library/heapq.html#theory