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.

136 CHAPTER 6 ■ ABSTRACTION<br />

In the original example, reduce takes care of the sum and the looping, while the lambda<br />

represents the expression sum + number. Let’s take a peek at what’s happening. The following<br />

defines a function for adding numbers that also prints out its arguments:<br />

def peek_sum(x, y):<br />

print 'Adding', x, 'and', y<br />

return x + y<br />

Let’s use this with reduce:<br />

>>> reduce(peek_sum, [1, 2, 3, 4, 5])<br />

Adding 1 and 2<br />

Adding 3 and 3<br />

Adding 6 and 4<br />

Adding 10 and 5<br />

15<br />

What happens is that reduce first adds 1 and 2, then adds the result with 3, and so on until<br />

all the elements have been added. Finally, after printing out all the operations it goes through,<br />

the sum (15) is returned.<br />

■Note There is a built-in function called sum, which returns the sum of a sequence. (It cannot be used to<br />

join a sequence of strings.)<br />

As another example, let’s imagine that you could only use max with two arguments (in fact, it<br />

works with entire sequences) and you wanted to use it on a sequence. Then you could use reduce:<br />

>>> reduce(max, numbers)<br />

119<br />

The max function is used here to return the maximum of two numbers, and instead of<br />

keeping track of a sum, reduce keeps track of the maximum so far. Let’s take another peek<br />

under the hood:<br />

def peek_max(x, y):<br />

print 'Finding max of', x, 'and', y<br />

return max(x, y)<br />

Just like peek_sum, peek_max prints out its arguments when it is executed. Let’s use it<br />

with reduce:<br />

>>> reduce(peek_max, [3, 5, 2, 6, 9, 2])<br />

Finding max of 3 and 5<br />

Finding max of 5 and 2<br />

Finding max of 5 and 6<br />

Finding max of 6 and 9<br />

Finding max of 9 and 2<br />

9

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

Saved successfully!

Ooh no, something went wrong!