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.

CHAPTER 10 ■ BATTERIES INCLUDED 223<br />

There are various in-place operations as well, with corresponding methods, as well as the<br />

basic methods add and remove. For more information, see the Python Library Reference, in the<br />

section about set types (http://python.org/doc/lib/types-set.html).<br />

■Tip If you need a function for finding, say, the union of two sets, you can simply use the unbound version<br />

of the union method, from the set type. This could be useful, for example, in concert with reduce:<br />

>>> mySets = []<br />

>>> for i in range(10):<br />

... mySets.append(set(range(i,i+5)))<br />

...<br />

>>> reduce(set.union, mySets)<br />

set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])<br />

Sets are mutable, and may therefore not be used, for example, as keys in dictionaries.<br />

Another problem is that sets themselves may only contain immutable (hashable) values, and<br />

thus may not contain other sets. Because sets of sets often occur in practice, this is something<br />

of a problem . . . Luckily, there is the frozenset type, which represents immutable (and, therefore,<br />

hashable) sets:<br />

>>> a = set()<br />

>>> b = set()<br />

>>> a.add(b)<br />

Traceback (most recent call last):<br />

File "", line 1, in ?<br />

TypeError: set objects are unhashable<br />

>>> a.add(frozenset(b))<br />

The frozenset constructor creates a copy of the given set, and is useful whenever you want<br />

to use a set either as a member of another set or as the key to a dictionary.<br />

Heaps<br />

Another well-known data structure is the heap, a kind of priority queue. A priority queue lets<br />

you add objects in an arbitrary order and at any time (possibly in-between the adding) find<br />

(and possibly remove) the smallest element. It does so much more efficiently than, say, using<br />

min on a list.<br />

In fact, there is no separate heap type in Python—only a module with some heapmanipulating<br />

functions. The module is called heapq (with the q standing for queue), and it<br />

contains six functions, the first four of which are directly related to heap manipulation. You<br />

must use a list as the heap object itself.<br />

The heappush function is used to add an item to a heap. Note that you shouldn’t use it on<br />

any old list—only one that has been built through the use of the various heap functions. The<br />

reason for this is that the order of the elements is important (even though it may look a bit<br />

haphazard; the elements aren’t exactly sorted).

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

Saved successfully!

Ooh no, something went wrong!