04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

224 CHAPTER 10 ■ BATTERIES INCLUDED<br />

>>> from heapq import *<br />

>>> from random import shuffle<br />

>>> data = range(10)<br />

>>> shuffle(data)<br />

>>> heap = []<br />

>>> for n in data:<br />

... heappush(heap, n)<br />

>>> heap<br />

[0, 1, 3, 6, 2, 8, 4, 7, 9, 5]<br />

>>> heappush(heap, 0.5)<br />

>>> heap<br />

[0, 0.5, 3, 6, 1, 8, 4, 7, 9, 5, 2]<br />

■Note The order of the elements isn’t as arbitrary as it seems. They aren’t in strictly sorted order, but there<br />

is one guarantee made: the element at position i is always greater than the one in position i // 2 (or,<br />

conversely, it’s smaller than the elements at positions 2*i and 2*i + 1). This is the basis for the underlying<br />

heap algorithm. This is called the heap property.<br />

The heappop function pops off the smallest element, which is always found at index 0, and<br />

makes sure that the smallest of the remaining element takes over this position (while preserving<br />

the heap property mentioned in the previous note). Even though popping the first element of a<br />

list isn’t efficient in general, it’s not a problem here, because heappop does some nifty shuffling<br />

behind the scenes:<br />

>>> heappop(heap)<br />

0<br />

>>> heappop(heap)<br />

0.5<br />

>>> heappop(heap)<br />

1<br />

>>> heap<br />

[2, 5, 3, 6, 9, 8, 4, 7]<br />

The heapify function takes an arbitrary list and makes it a legal heap (that is, it imposes the<br />

heap property mentioned in the previous note) through the least possible amount of shuffling.<br />

If you don’t build your heap from scratch with heappush, this is the function to use before starting<br />

to use heappush and heappop:<br />

>>> heap = [5, 8, 0, 3, 6, 7, 9, 1, 4, 2]<br />

>>> heapify(heap)<br />

>>> heap<br />

[0, 1, 5, 3, 2, 7, 9, 8, 4, 6]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!