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 6 ■ ABSTRACTION 133<br />

search recursively with new limits. You could even make this easier to use by making the limit<br />

specifications optional. You simply add the following conditional to the beginning of the<br />

function definition:<br />

def search(sequence, number, lower=0, upper=None):<br />

if upper is None: upper = len(sequence)-1<br />

...<br />

Now, if you don’t supply the limits, they are set to the first and last positions of the sequence.<br />

Let’s see if this works:<br />

>>> seq = [34, 67, 8, 123, 4, 100, 95]<br />

>>> seq.sort()<br />

>>> seq<br />

[4, 8, 34, 67, 95, 100, 123]<br />

>>> search(seq, 34)<br />

2<br />

>>> search(seq, 100)<br />

5<br />

But why go to all this trouble, you ask? For one thing, you could simply use the list method<br />

index, and if you wanted to implement this yourself, you could just make a loop starting at the<br />

beginning and iterating along until you found the number.<br />

Sure. Using index is just fine. But using a simple loop may be a bit inefficient. Remember I<br />

said you needed seven questions to find one number (or position) among 100? And the loop<br />

obviously needs 100 questions in the worst-case scenario. Big deal, you say. But if the list has<br />

100,000,000,000,000,000,000,000,000,000,000,000 elements, and the same number of questions<br />

with a loop (perhaps a somewhat unrealistic size for a Python list), this sort of thing starts to<br />

matter. Binary search would then need only 117 questions. Pretty efficient, huh?<br />

■Tip There is a standard library module called bisect, which implements binary search very efficiently.<br />

Throwing Functions Around<br />

By now, you are probably used to using functions just like other objects (strings, number,<br />

sequences, and so on) by assigning them to variables, passing them as parameters, and<br />

returning them from other functions. Some programming languages (such as Scheme or LISP)<br />

use functions in this way to accomplish almost everything. Even though you usually don’t rely<br />

that heavily on functions in Python (you usually make your own kinds of objects—more about<br />

that in the next chapter), you can. This section describes a few functions that are useful for this<br />

sort of “functional programming.” These functions are map, filter, reduce, and apply.

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

Saved successfully!

Ooh no, something went wrong!