Lambda to map reduce and filter
Lambda to map reduce and filter
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_3964/2418066946.py in <module>
7
8 hi=greetings() #assisgning returned reference by outer function in some name
----> 9 print(say_hi()) #It is still a local resources
While normal functions are defined using the def keyword in Python, anonymous functions are
defined using the lambda keyword.
2.In the definition of the lambdas, the arguments don’t have parentheses around them.
3.Multi-argument functions (functions that take more than one argument) are expressed in
Python lambdas by listing arguments and separating them with a comma (,) but without
surrounding them with parentheses:
Python exposes higher-order functions as built-in functions or in the standard library. Examples
include map(), filter(), functools.reduce(), as well as key functions like sort(), sorted(), min(), and
max().
In [2]:
localhost:8888/nbconvert/html/CS Lecture-1.ipynb?download=false 27/36
2/3/22, 4:08 PM CS Lecture-1
def add(x,y):
z=x+y
return z
print(add(5,3))
In [6]:
#Addition using anonymous/lambda function
In [7]:
#checking the type of defined lambda function
<class 'function'>
In [8]:
#calling the lambda function through its referenced variable
#s has the reference of defined lambda function..
#so s can be called like a normal function by passing parameters mentioned in lambda
#expression written in lambda function will be evaluated and it return the value.
print(s(7,5))
12
In [9]:
#Square of a number using lambda
lambda x:(x*x)
<function __main__.<lambda>(x)>
Out[9]:
In [10]:
#Square of a number using lambda
sq=lambda x:(x*x)
print(sq)
In [11]:
#Square of a number using lambda
sq=lambda x:(x*x)
print(sq())
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_9408/954540975.py in <module>
2
3 sq=lambda x:(x*x)
----> 4 print(sq())
In [15]:
#Square of a number using lambda
sq=lambda x:(x*x)
print(sq(x=8)) #Parameter passed as keyword argument.
print(sq(5)) #Parameter passed as positional argument.
64
25
In [1]:
# A lambda function to calculate simple interest
250.0
2500.0
In [3]:
#Lambda with default arguments:
500.0
1250.0
In [7]:
#Lambda function with user-defined function:
doubler=multiplier(2)
print(doubler(10))
print(doubler(5))
tripler=multiplier(3)
print(tripler(10))
20
10
30
In [8]:
x=10
y=15
z=x+y
if x>y:
print (z)
else:
print (x-y)
-5
In [ ]:
#Using "If-else" statement with lambda function.
#it's not advisable to use lambda for conditional statement.
#A conditional statement becomes very confusing when it's written like expression.
In [9]:
greater=lambda x,y: x if x>y else y
In [10]:
even_odd=lambda x:print("Even") if x%2==0 else print("Odd")
even_odd(12)
even_odd(7)
even_odd(9)
Even
Odd
Odd
In [11]:
#Lambda with non-keyword variable length arguments
var()
var(1)
var(1,2,3,4,5)
()
(1,)
(1, 2, 3, 4, 5)
In [14]:
#Lambda with keyword variable length arguments
kvar()
kvar(a=1,b=2,c=3,d=4,e=5)
{}
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
As mentioned earlier, map(), filter() and reduce() are inbuilt functions of Python. These functions
enable the functional programming aspect of Python. In functional programming, the arguments
passed are the only factors that decide upon the output. These functions can take any other
function as a parameter and can be supplied to other functions as parameters as well.
MAP() FUNCTION:
The map() function is a type of higher-order function. As mentioned earlier, this function takes
another function as a parameter along with a sequence of iterables and returns an output after
applying the function to each iterable present in the sequence.
Syntax: map(function,iterables)
Here, the function defines an expression that is in turn applied to the iterables. The map function
can take user-defined functions as well as lambda functions as a parameter.
User-defined functions can be sent to the map() method. The user or programmer is the only one who can
change the parameters of these functions. For example look at the code mention below:
In [4]:
def cs(a):
return a*a
x=map(cs,(1,2,3,4,5,6,7,8,9))
print(x)
print(tuple(x))
output=map(lambda x:x+3,[1,2,3,4,5])
print(output)
print(list(output))
In [9]:
def doubler(x):
return x*2
li=[10,20,30,40,50]
new_list=map(doubler,li)
new_list=list(new_list)
print(new_list)
In [19]: keshav=[11,22,33,44,55]
do_li=list(map((lambda x:x*2),keshav))
print(do_li)
In [11]:
# map function with more than one iterables
#simple interest with map function
si_li=list(map((lambda p,r,t:p*r*t/100),pli,rli,tli))
print(si_li)
In [14]:
#Map function can also use built-in or library function as arguments
num=['10','20','30','40','50']
#a map function to convert each element of the above list into integer
#so each elements will be typecasted in integer by using int function
num_li=list(map(int,num))
print(num_li)
In [24]:
#Program to calculate length of a string using map function
#built-in function "len()" will be used in map
st_li=("amartya","kush","aslam","shivangi","diksha","kavya")
st_len=tuple(map(len,st_li))
print(st_len)
(7, 4, 5, 8, 6, 5)
FILTER FUNCTION:
1. The filter() function is used to create an output list consisting of values for which the function
returns true.
4. If None,then the function defaults to identity function which returns false if any elements are
false.
def bekar_class(x):
if x>=5:
return x
y = filter(bekar_class, (1,2,3,4,5,6,7,8))
print(y)
print(list(y))
#As you can see, y is the filter object and the list
#is a list of values that are true for the condition (x>=5).
In [27]:
y = filter(lambda x: (x>=5), (1,2,3,4,5,6,7,8))
print(list(y))
[5, 6, 7, 8]
In [2]:
#Filter function returns the elements of seq which produce True as a result
#for the condtion in function
seq=[True,False,True,True,False,False,None]
res=list(filter(lambda x:x,seq))
print(res)
In [4]:
#Filter out all the positive integers from a given list
cs=[-22,1,-34,45,67,-98,78,11,-65,65]
cs_obj=list(filter(lambda x:x>0,cs))
print("Positive Numbers are: ",cs_obj)
REDUCE() FUNCTION:
1. Python's reduce() implement a mathematical technique commonly known as "Folding" or
"Reduction". It is used to reduce a list of items to a single cumulative value.
3. The function applied to the first two items in an iteable and generate a partial result.
4. The partial result,together with the third item in the iterable to generate another partial
result and the process is repeated untill the iterable is exhausted and then return a single
cumulative value.
5. Reduce() function is available in "functools module". So before using it we must import in our
scope. "from functools import reduce"
In [10]:
#Example reduce() function:
morning=[2,4,5,6,7,8,1,10]
cs=reduce(lambda x,y:x+y,morning)
print("Sum of elements in list is: ",cs)
In [13]:
from functools import reduce
l=[10,20,30,40]
s=reduce(lambda x,y:x+y,l,1000) #third argument will be seed for the cumulative resul
print(s)
1100
In [14]:
#Sum of only even numbers using reduce in a given list
bolo=[1,2,3,4,5,6,7,8,9,10,11,12]
In [15]:
#To find the max value in a list using reduce
li2=[22,33,4,5,77,99,1,43]
print(mx)
99
In [21]:
from functools import reduce
66
In [4]:
from functools import reduce
cs=[1,2,3,4,5,6,7,8]
sum_lk=reduce(lambda x,y: x+y,list(filter(lambda x:x%2==0,list(map(int,cs)))))
print (sum_lk)
20
In [6]:
#filter all the prime numbers within a given range and compute its summation.
def prime(n):
if n<=1:
return False
for i in range(2,n):
if n%i==0:
return False
else:
return True
#input range
sum_cs=reduce(lambda x,y:x+y,prime_cs)
print("Sum of prime numbers is:",sum_cs)
In [11]:
#Find all the cubes of each element in a list which are divisible by 3
jordar=[10,20,30,40,50,60,70,80,90,100]
div_jordar=list(filter(lambda x: x%3==0,cube_jordar))
print("Divisible by 3: ",div_jordar)
Cubes are: [1000, 8000, 27000, 64000, 125000, 216000, 343000, 512000, 729000, 100000
0]
Divisible by 3: [27000, 216000, 729000]
[27000, 216000, 729000]
In [ ]: