04.08.2014 Views

o_18ufhmfmq19t513t3lgmn5l1qa8a.pdf

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 10 ■ BATTERIES INCLUDED 225<br />

The heapreplace function is not quite as commonly used as the others. It pops the smallest<br />

element off the heap and then pushes a new element onto it. This is more efficient than a<br />

heappop followed by a heappush:<br />

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

0<br />

>>> heap<br />

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

>>> heapreplace(heap, 10)<br />

0.5<br />

>>> heap<br />

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

The remaining two functions of the heapq module, nlargest(n, iter) and<br />

nsmallest(n, iter), are used to find the n largest or smallest elements, respectively, of any<br />

iterable object iter. You could do this by using sorting (for example, using the sorted function)<br />

and slicing, but the heap algorithm is faster and more memory-efficient (and, not to mention,<br />

easier to use).<br />

Deques (and Other Collections)<br />

Double-ended queues, or deques, can be useful when you need to remove elements in the<br />

order in which they were added. In Python 2.4, the collections module was added, which<br />

contains the deque type.<br />

■Note As of Python 2.4, the collections module only contains the deque type. Possible future additions<br />

are B-trees and Fibonacci heaps.<br />

A deque is created from an iterable object (just like sets) and has several useful methods:<br />

>>> from collections import deque<br />

>>> q = deque(range(5))<br />

>>> q.append(5)<br />

>>> q.appendleft(6)<br />

>>> q<br />

deque([6, 0, 1, 2, 3, 4, 5])<br />

>>> q.pop()<br />

5<br />

>>> q.popleft()<br />

6<br />

>>> q.rotate(3)<br />

>>> q<br />

deque([2, 3, 4, 0, 1])<br />

>>> q.rotate(-1)<br />

>>> q<br />

deque([3, 4, 0, 1, 2])

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

Saved successfully!

Ooh no, something went wrong!