Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 [Python-tut] Using reduce
Index -> General Programming
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
wtd




PostPosted: 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
Sponsor
Sponsor
Sponsor
sponsor
Display posts from previous:   
   Index -> General Programming
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 1 Posts ]
Jump to:   


Style:  
Search: