Friday, October 4, 2013

Lambda in Python (Map, Reduce and Filter)

Map, Reduce and Filter using Lambda in Python

1. Map
>>>map(lambda x:x*x, range(1,10))
>>>[1, 4, 9, 16, 25, 36, 49, 64, 81]

2. Reduce
>>>reduce(lambda x,y: x+y, range(1,10))
>>>45

3. Filter
>>>filter(lambda x: x % 2 != 0, range(1,20))
>>>[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]

ex1: Add sum of all even number from 1 to 20
>>>reduce(lambda x,y: x+y, filter(lambda x: x % 2 == 0, range(1,20)))
>>>90

ex2: lambda as return function
>>>g = lambda x: x**2
>>>print g(2)
>>>4

ex3: like partial function
>>>def increament(n):
>>>    return lambda x: x + n
>>>f = increment(10)
>>>print f(6)
>>>16
or
>>>print increament(6)(10)
>>>16

ex4: prime numbers between 1-100
>>>nums = range(2,100)
>>>for i in range(2,8):
>>>    nums = filter(lambda x: x == i or x % i, nums)
>>>print nums
>>>[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

ex5: Letter count
>>>print map(lambda w: len(w), 'It has been raining since this morning'.split())
>>>[2, 3, 4, 7, 5, 4, 7]

ex6: Functional Style of adding
>>> from operator import add
>>> expr = "28+32+++32++39"
>>> print reduce(add, map(int, filter(bool, expr.split("+"))))
>>> 131

No comments:

Post a Comment