wtd
|
Posted: Fri Jul 29, 2005 2:25 pm Post subject: [Python-tut] Using reduce |
|
|
The "reduce" function is an incredibly powerful, but often overlooked part of Python's standard library. With it we can glimpse a bit of the power functional languages have for transforming data.
Let's look at a simple example. I want to write a function which calculates the factorial of a number. This is pretty simple.
code: | >>> def factorial(number):
... fact = 1
... for n in xrange(2, number + 1):
... fact *= n
... return fact
...
>>> factorial(4)
24 |
But if we really think about what this function is doing, we realize it's just getting the product of the range 1 .. N.
So, how can we more efficiently write a "product" function?
Enter "reduce".
This function is what, in a functional language we'd call a "fold". That word is perhaps easier to use in explaining the concept.
Imagine a long piece of paper with numbers printed on it every few inches. This represents a list or array of values. We also have some other thing at the beginning of the list.
Now, fold up the first value, and apply it and the other thing at the head of the list to a function. You'll get back a new value of the same type as the thing that was at the head of the list. Now, we do the same thing with this value and the second value in the list, and so on until we get to the end of the list.
Let's look at our product function again. To use reduce on this we'll need three things:
- A function for dealing with that first thing and the element from the list.
- A list of values.
- Some first value outside of the list.
code: | >>> reduce(lambda a, b: a * b, xrange(2, 5), 1)
24 |
|
|
|