Friday, 20 September 2013

Filter(), Map() and Reduce()-----> Tools for functional programming

Filter() map() and reduce() are built in functions. These are very useful while used with lists. Here are the details.

Filter()


Syntax:
                filter(function,sequence)


returns a sequence consisting of those elements from the sequence for which function(element) is true. If sequence is a string or tuple, the result will be of the same type, otherwise, it is always a list.
 For example, to compute a sequence of numbers not divisible by 2 and 3:
 >>> def f(x):
...     return ((x%2!=0) and (x%3!=0))
...
>>> filter(f,range(0,10))
[1, 5, 7]

Map()

Syntax:
               map(function,sequence)
Calls the function() for each value in the sequence and stores the return value in a list. For example:
>>> def cube(x):
...     return x*x*x
...
>>> map(cube,range(10))
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
>>> 
More than one sequence may be passed; the function must then have as many arguments as there are sequences and is called with the corresponding item from each sequence (or None if some sequence is shorter than another). For example:
>>> def f(x,y):
...     return x+y
...
>>> seq=range(8)
>>> map(f,seq,seq)
[0, 2, 4, 6, 8, 10, 12, 14]
>>>

 

Reduce()

Syntax:
                  reduce(function,sequence)              

returns a single value constructed by calling the binary function "function" on the first two items of the sequence, then on the result and the next item, and so on. For example, to compute the sum of the numbers 1 through 10:
>>>
>>> def f(x,y):
...     return x+y
... 
>>>reduce(f,range(1,11));
55

If there’s only one item in the sequence, its value is returned; if the sequence is empty, an exception is raised.A third argument can be passed to indicate the starting value.

0 comments:

Post a Comment