SlideShare a Scribd company logo
2
Digitalpadm.com
2[Date]
3.5.2 map function in python
The map() function in Python takes in a function and a list as argument. The function is
called with a lambda function with list as parameter.
It returns an output as list which contains all the lambda modified items returned by
that function for each item.
3.5.2.1 Example - Find square of each number from number list using map
def square(x):
return x*x
squarelist = map(square, [1, 2, 3, 4, 5])
for x in squarelist:
print(x,end=',')
Output
1,4,9,16,25,
Here map function passes list elements as parameters to function. Same function can be
implemented using lambda function as below,
Example -
squarelist = map(lambda x: x*x, [1, 2, 3, 4, 5])
for x in squarelist:
print(x)
3.5.2.2 Example - lambda function to find length of strings
playernames = ["John", "Martin", "SachinTendulkar"]
playernamelength = map(lambda string: len(string), playernames)
for x in playernamelength:
print(x, end="")
Output
4 6 15
Lambda functions allow you to create “inline” functions which are useful for functional
programming.
Most read
3
Digitalpadm.com
3[Date]
3.5.3 filter function in python
filter() function in Python takes in a function with list as arguments.
It filters out all the elements of a list, for which the function returns True.
3.5.3.1 Example - lambda function to find player names whose name length is 4
playernames = ["John", "Martin", "SachinTendulkar","Ravi"]
result = filter(lambda string: len(string)==4, playernames)
for x in result:
print(x)
Output
John
Ravi
3.5.4 reduce function in python
reduce() function in Python takes in a function with a list as argument.
It returns output as a new reduced list. It performs a repetitive operation over the
pairs of the list.
3.5.4.1 Example - lambda function to find sum of list numbers.
from functools import reduce
numlist = [12, 22, 10, 32, 52, 32]
sum = reduce((lambda x, y: x + y), numlist)
print (sum)
Output
160
Here it performs repetitive add operations on consecutive pairs. it performs (12+22) then
((12+22)+10) as for other elements of the list.
Most read
4
Digitalpadm.com
4[Date]
3.6 Programs on User Defined Functions
3.6.1 Python User defined function to convert temperature from c to f
Steps
Define function convert_temp & implement formula f=1.8*c +32
Read temperature in c
Call function convert_temp & pass parameter c
Print result as temperature in fahrenheit
Code
def convert_temp(c):
f= 1.8*c + 32
return f
c= float(input("Enter Temperature in C: "))
f= convert_temp(c)
print("Temperature in Fahrenheit: ",f)
Output
Enter Temperature in C: 37
Temperature in Fahrenheit: 98.60
In above code, we are taking the input from user, user enters the temperature in Celsius
and the function convert_temp converts the entered value into Fahrenheit using the
conversion formula 1.8*c + 32
3.6.2 Python User defined function to find max, min, average of given list
In this program, function takes a list as input and return number as output.
Steps
Define max_list, min_list, avg_list functions, each takes list as parameter
Most read
Digitalpadm.com
1[Date]
Python lambda functions with filter, map & reduce function
3.5.1 Lambda functions
A small anonymous (unnamed) function can be created with the lambda keyword.
lambda expressions allow a function to be created and passed in one line of code.
It can be used as an argument to other functions. It is restricted to a single expression
lambda arguments : expression
It can take any number of arguments,but have a single expression only.
3.5.1.1 Example - lambda function to find sum of square of two numbers
z = lambda x, y : x*x + y*y
print(z(10,20)) # call to function
Output
500
Here x*x + y*y expression is implemented as lambda function.
after keyword lambda, x & y are the parameters and after : expression to evaluate is
x*x+ y*y
3.5.1.2 Example - lambda function to add two numbers
def sum(a,b):
return a+b
is similar to
result= lambda a, b: (a + b)
lambda function allows you to pass functions as parameters.
Digitalpadm.com
2[Date]
3.5.2 map function in python
The map() function in Python takes in a function and a list as argument. The function is
called with a lambda function with list as parameter.
It returns an output as list which contains all the lambda modified items returned by
that function for each item.
3.5.2.1 Example - Find square of each number from number list using map
def square(x):
return x*x
squarelist = map(square, [1, 2, 3, 4, 5])
for x in squarelist:
print(x,end=',')
Output
1,4,9,16,25,
Here map function passes list elements as parameters to function. Same function can be
implemented using lambda function as below,
Example -
squarelist = map(lambda x: x*x, [1, 2, 3, 4, 5])
for x in squarelist:
print(x)
3.5.2.2 Example - lambda function to find length of strings
playernames = ["John", "Martin", "SachinTendulkar"]
playernamelength = map(lambda string: len(string), playernames)
for x in playernamelength:
print(x, end="")
Output
4 6 15
Lambda functions allow you to create “inline” functions which are useful for functional
programming.
Digitalpadm.com
3[Date]
3.5.3 filter function in python
filter() function in Python takes in a function with list as arguments.
It filters out all the elements of a list, for which the function returns True.
3.5.3.1 Example - lambda function to find player names whose name length is 4
playernames = ["John", "Martin", "SachinTendulkar","Ravi"]
result = filter(lambda string: len(string)==4, playernames)
for x in result:
print(x)
Output
John
Ravi
3.5.4 reduce function in python
reduce() function in Python takes in a function with a list as argument.
It returns output as a new reduced list. It performs a repetitive operation over the
pairs of the list.
3.5.4.1 Example - lambda function to find sum of list numbers.
from functools import reduce
numlist = [12, 22, 10, 32, 52, 32]
sum = reduce((lambda x, y: x + y), numlist)
print (sum)
Output
160
Here it performs repetitive add operations on consecutive pairs. it performs (12+22) then
((12+22)+10) as for other elements of the list.
Digitalpadm.com
4[Date]
3.6 Programs on User Defined Functions
3.6.1 Python User defined function to convert temperature from c to f
Steps
Define function convert_temp & implement formula f=1.8*c +32
Read temperature in c
Call function convert_temp & pass parameter c
Print result as temperature in fahrenheit
Code
def convert_temp(c):
f= 1.8*c + 32
return f
c= float(input("Enter Temperature in C: "))
f= convert_temp(c)
print("Temperature in Fahrenheit: ",f)
Output
Enter Temperature in C: 37
Temperature in Fahrenheit: 98.60
In above code, we are taking the input from user, user enters the temperature in Celsius
and the function convert_temp converts the entered value into Fahrenheit using the
conversion formula 1.8*c + 32
3.6.2 Python User defined function to find max, min, average of given list
In this program, function takes a list as input and return number as output.
Steps
Define max_list, min_list, avg_list functions, each takes list as parameter
Digitalpadm.com
5[Date]
Initialize list lst with 10 numbers
Call these functions and print max, min and avg values
Code
def max_list(lst):
maxnum=0
for x in lst:
if x>maxnum:
maxnum=x
return maxnum
def min_list(lst):
minnum=1000 # max value
for x in lst:
if x<minnum:
minnum=x
return minnum
def avg_list(lst):
return sum(lst) / len(lst)
# main function
lst = [52, 29, 155, 341, 357, 230, 282, 899]
maxnum = max_list(lst)
minnum = min_list(lst)
avgnum = avg_list(lst)
print("Max of the list =", maxnum)
print("Min of the list =", minnum)
print("Avg of the list =", avgnum)
Output
Max of the list = 899
Min of the list = 29
Avg of the list = 293.125
3.6.3 Python User defined function to print the Fibonacci series
In this program, function takes a number as input and return list as output.
In mathematics, the Fibonacci numbers are the numbers in the sequence such as for each
number is the sum of its previous two numbers.
Digitalpadm.com
6[Date]
Following is the example of Fibonacci series up to 6 Terms
1, 1, 2, 3, 5, 8
The sequence Fn of Fibonacci numbers is recursively represented as Fn-1 + Fn-2.
Implement function to return Fibonacci series.
Code
def fiboseries(n): # return Fibonacci series up to n
result = []
a= 1
b=0
cnt=1
c=0
while cnt <=n:
c=a+b
result.append(c)
a=b
b=c
cnt=cnt+1
return result
terms=int(input("Enter No. of Terms: "))
result=fiboseries(terms)
print(result)
Output
Enter No. of Terms: 8
[1, 1, 2, 3, 5, 8, 13, 21]
Enter No. of Terms: 10
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
In code above, fiboseries function is implemented which takes numbers of terms as
parameters and returns the fibonacci series as an output list.
Initialize the empty list, find each fibonacci term and append to the list. Then return list
as output
3.6.4 Python User defined function to reverse a String without using Recursion
In this program, function takes a string as input and returns reverse string as output.
Digitalpadm.com
7[Date]
Steps
Implement reverse_string function , Use string slicing to reverse the string.
Take a string as Input
Call reverse_function & pass string
Print the reversed string.
Code
def reverse_string(str):
return str[::-1]
nm=input("Enter a string: ")
result=reverse_string(nm)
print("Reverse of the string is: ", result)
Output
Enter a string: Soft
Reverse of the string is: tfoS
In this code, one line reverse_string is implemented which takes string as parameter and
returns string slice as whole from last character. -1 is a negative index which gives the last
character. Result variable holds the return value of the function and prints it on screen.
3.6.5 Python User defined function to find the Sum of Digits in a Number
Steps
Implement function sumdigit takes number as parameter
Input a Number n
Call function sumdigit
Print result
Code
def sumdigit(n):
sumnum = 0
while (n != 0):
Digitalpadm.com
8[Date]
sumnum = sumnum + int(n % 10)
n = int(n/10)
return sumnum
# main function
n = int(input("Enter number: "))
result=sumdigit(n)
print("Result= ",result)
Output
Enter number: 5965
Result= 25
Enter number: 1245
Result= 12
In this code, Input number n, pass to sumdigit function, sum of digit of given number is
computed using mod operator (%). Mod a given number by 10 and add to the sum variable.
Then divide the number n by 10 to reduce the number. If number n is non zero then repeat
the same steps.
3.6.6 Python Program to Reverse a String using Recursion
Steps
Implement recursive function fibo which takes n terms
Input number of terms n
Call function fibo & pass tems
Print result
Code
def fibo(n):
if n <= 1:
return 1
Digitalpadm.com
9[Date]
else:
return(fibo(n-1) + fibo(n-2))
terms = int(input("Enter number of terms: "))
print("Fibonacci sequence:")
for i in range(terms):
print(fibo(i),end="")
Output
Enter number of terms: 8
Fibonacci sequence:
1 1 2 3 5 8 13 21
In above code, fibo function is implemented using a recursive function, here n<=1 is
terminating condition, if true the return 1 and stops the recursive function. If false return
sum of call of previous two numbers. fibo function is called from the main function for
each term.
3.6.7 Python Program to Find the Power of a Number using recursion
InpuSteps
t base and exp value
call recursive function findpower with parameter base & exp
return base number when the power is 1
If power is not 1, return base*findpower(base,exp-1)
Print the result.
Code
def findpower(base,exp):
if(exp==1):
return(base)
else:
return(base*findpower(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exp: "))
print("Result: ",findpower(base,exp))
Digitalpadm.com
10[Date]
Output
Enter base: 7
Enter exp: 3
Result: 343
In this code, findpower is a recursive function which takes base and exp as numeric parameters.
Here expt==1 is the terminating condition, if this true then return the base value. If terminating
condition is not true then multiply base value with decrement exp value and call same function

More Related Content

What's hot (20)

Python : Functions
Python : FunctionsPython : Functions
Python : Functions
Emertxe Information Technologies Pvt Ltd
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
baabtra.com - No. 1 supplier of quality freshers
 
python Function
python Function python Function
python Function
Ronak Rathi
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
Shakti Singh Rathore
 
Python programming : Exceptions
Python programming : ExceptionsPython programming : Exceptions
Python programming : Exceptions
Emertxe Information Technologies Pvt Ltd
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Kamal Acharya
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
Edureka!
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
Emertxe Information Technologies Pvt Ltd
 
Control Structures in Python
Control Structures in PythonControl Structures in Python
Control Structures in Python
Sumit Satam
 
How to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | EdurekaHow to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | Edureka
Edureka!
 
Python programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphismPython programming : Inheritance and polymorphism
Python programming : Inheritance and polymorphism
Emertxe Information Technologies Pvt Ltd
 
Decision Making & Loops
Decision Making & LoopsDecision Making & Loops
Decision Making & Loops
Akhil Kaushik
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
Praveen M Jigajinni
 
Introduction to numpy Session 1
Introduction to numpy Session 1Introduction to numpy Session 1
Introduction to numpy Session 1
Jatin Miglani
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
Manav Prasad
 
Python-Encapsulation.pptx
Python-Encapsulation.pptxPython-Encapsulation.pptx
Python-Encapsulation.pptx
Karudaiyar Ganapathy
 
Namespaces
NamespacesNamespaces
Namespaces
Sangeetha S
 
Python Generators
Python GeneratorsPython Generators
Python Generators
Akshar Raaj
 
python Function
python Function python Function
python Function
Ronak Rathi
 
Functions in python slide share
Functions in python slide shareFunctions in python slide share
Functions in python slide share
Devashish Kumar
 
Java 8 presentation
Java 8 presentationJava 8 presentation
Java 8 presentation
Van Huong
 
Python Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | EdurekaPython Basics | Python Tutorial | Edureka
Python Basics | Python Tutorial | Edureka
Edureka!
 
Control Structures in Python
Control Structures in PythonControl Structures in Python
Control Structures in Python
Sumit Satam
 
How to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | EdurekaHow to use Map() Filter() and Reduce() functions in Python | Edureka
How to use Map() Filter() and Reduce() functions in Python | Edureka
Edureka!
 
Decision Making & Loops
Decision Making & LoopsDecision Making & Loops
Decision Making & Loops
Akhil Kaushik
 
Introduction to numpy Session 1
Introduction to numpy Session 1Introduction to numpy Session 1
Introduction to numpy Session 1
Jatin Miglani
 
Python Generators
Python GeneratorsPython Generators
Python Generators
Akshar Raaj
 

Similar to Python lambda functions with filter, map & reduce function (20)

Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
VisnuDharsini
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
priestmanmable
 
Python for Data Science function third module ppt.pptx
Python for Data Science  function third module ppt.pptxPython for Data Science  function third module ppt.pptx
Python for Data Science function third module ppt.pptx
bmit1
 
function_xii-BY APARNA DENDRE (1).pdf.pptx
function_xii-BY APARNA DENDRE (1).pdf.pptxfunction_xii-BY APARNA DENDRE (1).pdf.pptx
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
 
Python-Functions.pptx
Python-Functions.pptxPython-Functions.pptx
Python-Functions.pptx
Karudaiyar Ganapathy
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
jamvantsolanki
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
advanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with pythonadvanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with python
barmansneha1204
 
Advanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learnersAdvanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learners
barmansneha1204
 
Advance Programming Slide lecture 4.pptx
Advance Programming Slide lecture 4.pptxAdvance Programming Slide lecture 4.pptx
Advance Programming Slide lecture 4.pptx
mohsinfareed780
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
vishnupriyapm4
 
Functions in python, types of functions in python
Functions in python, types of functions in pythonFunctions in python, types of functions in python
Functions in python, types of functions in python
SherinRappai
 
Functions-.pdf
Functions-.pdfFunctions-.pdf
Functions-.pdf
arvdexamsection
 
Python Lecture 4
Python Lecture 4Python Lecture 4
Python Lecture 4
Inzamam Baig
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
vishnupriyapm4
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
Rick Copeland
 
Chapter 02 functions -class xii
Chapter 02   functions -class xiiChapter 02   functions -class xii
Chapter 02 functions -class xii
Praveen M Jigajinni
 
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptxCLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
seccoordpal
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
Unit 2 - Functions in python - Prof Jishnu M S
Unit 2 - Functions in python - Prof Jishnu M SUnit 2 - Functions in python - Prof Jishnu M S
Unit 2 - Functions in python - Prof Jishnu M S
jishnums10
 
Functions in advanced programming
Functions in advanced programmingFunctions in advanced programming
Functions in advanced programming
VisnuDharsini
 
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docxISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
priestmanmable
 
Python for Data Science function third module ppt.pptx
Python for Data Science  function third module ppt.pptxPython for Data Science  function third module ppt.pptx
Python for Data Science function third module ppt.pptx
bmit1
 
function_xii-BY APARNA DENDRE (1).pdf.pptx
function_xii-BY APARNA DENDRE (1).pdf.pptxfunction_xii-BY APARNA DENDRE (1).pdf.pptx
function_xii-BY APARNA DENDRE (1).pdf.pptx
g84017903
 
Python Programming unit5 (1).pdf
Python Programming unit5 (1).pdfPython Programming unit5 (1).pdf
Python Programming unit5 (1).pdf
jamvantsolanki
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
Muthu Vinayagam
 
advanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with pythonadvanced python for those who have beginner level experience with python
advanced python for those who have beginner level experience with python
barmansneha1204
 
Advanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learnersAdvanced Python after beginner python for intermediate learners
Advanced Python after beginner python for intermediate learners
barmansneha1204
 
Advance Programming Slide lecture 4.pptx
Advance Programming Slide lecture 4.pptxAdvance Programming Slide lecture 4.pptx
Advance Programming Slide lecture 4.pptx
mohsinfareed780
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
vishnupriyapm4
 
Functions in python, types of functions in python
Functions in python, types of functions in pythonFunctions in python, types of functions in python
Functions in python, types of functions in python
SherinRappai
 
Unit 2function in python.pptx
Unit 2function in python.pptxUnit 2function in python.pptx
Unit 2function in python.pptx
vishnupriyapm4
 
Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)Python Functions (PyAtl Beginners Night)
Python Functions (PyAtl Beginners Night)
Rick Copeland
 
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptxCLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
CLASS-11 & 12 ICT PPT PYTHON PROGRAMMING.pptx
seccoordpal
 
Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...Processing data with Python, using standard library modules you (probably) ne...
Processing data with Python, using standard library modules you (probably) ne...
gjcross
 
Unit 2 - Functions in python - Prof Jishnu M S
Unit 2 - Functions in python - Prof Jishnu M SUnit 2 - Functions in python - Prof Jishnu M S
Unit 2 - Functions in python - Prof Jishnu M S
jishnums10
 
Ad

Recently uploaded (20)

Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
Journal of Soft Computing in Civil Engineering
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
Ppt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineeringPpt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineering
ravindrabodke
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt3. What is the principles of Teamwork_Module_V1.0.ppt
3. What is the principles of Teamwork_Module_V1.0.ppt
engaash9
 
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptxFINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
FINAL 2013 Module 20 Corrosion Control and Sequestering PPT Slides.pptx
kippcam
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Artificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowyArtificial Power 2025 raport krajobrazowy
Artificial Power 2025 raport krajobrazowy
dominikamizerska1
 
Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)Strength of materials (Thermal stress and strain relationships)
Strength of materials (Thermal stress and strain relationships)
pelumiadigun2006
 
Computer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdfComputer_vision-photometric_image_formation.pdf
Computer_vision-photometric_image_formation.pdf
kumarprem6767merp
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant ConversionStructural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Ppt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineeringPpt on the related on the solar power system for electric vehicle engineering
Ppt on the related on the solar power system for electric vehicle engineering
ravindrabodke
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
Ad

Python lambda functions with filter, map & reduce function

  • 1. Digitalpadm.com 1[Date] Python lambda functions with filter, map & reduce function 3.5.1 Lambda functions A small anonymous (unnamed) function can be created with the lambda keyword. lambda expressions allow a function to be created and passed in one line of code. It can be used as an argument to other functions. It is restricted to a single expression lambda arguments : expression It can take any number of arguments,but have a single expression only. 3.5.1.1 Example - lambda function to find sum of square of two numbers z = lambda x, y : x*x + y*y print(z(10,20)) # call to function Output 500 Here x*x + y*y expression is implemented as lambda function. after keyword lambda, x & y are the parameters and after : expression to evaluate is x*x+ y*y 3.5.1.2 Example - lambda function to add two numbers def sum(a,b): return a+b is similar to result= lambda a, b: (a + b) lambda function allows you to pass functions as parameters.
  • 2. Digitalpadm.com 2[Date] 3.5.2 map function in python The map() function in Python takes in a function and a list as argument. The function is called with a lambda function with list as parameter. It returns an output as list which contains all the lambda modified items returned by that function for each item. 3.5.2.1 Example - Find square of each number from number list using map def square(x): return x*x squarelist = map(square, [1, 2, 3, 4, 5]) for x in squarelist: print(x,end=',') Output 1,4,9,16,25, Here map function passes list elements as parameters to function. Same function can be implemented using lambda function as below, Example - squarelist = map(lambda x: x*x, [1, 2, 3, 4, 5]) for x in squarelist: print(x) 3.5.2.2 Example - lambda function to find length of strings playernames = ["John", "Martin", "SachinTendulkar"] playernamelength = map(lambda string: len(string), playernames) for x in playernamelength: print(x, end="") Output 4 6 15 Lambda functions allow you to create “inline” functions which are useful for functional programming.
  • 3. Digitalpadm.com 3[Date] 3.5.3 filter function in python filter() function in Python takes in a function with list as arguments. It filters out all the elements of a list, for which the function returns True. 3.5.3.1 Example - lambda function to find player names whose name length is 4 playernames = ["John", "Martin", "SachinTendulkar","Ravi"] result = filter(lambda string: len(string)==4, playernames) for x in result: print(x) Output John Ravi 3.5.4 reduce function in python reduce() function in Python takes in a function with a list as argument. It returns output as a new reduced list. It performs a repetitive operation over the pairs of the list. 3.5.4.1 Example - lambda function to find sum of list numbers. from functools import reduce numlist = [12, 22, 10, 32, 52, 32] sum = reduce((lambda x, y: x + y), numlist) print (sum) Output 160 Here it performs repetitive add operations on consecutive pairs. it performs (12+22) then ((12+22)+10) as for other elements of the list.
  • 4. Digitalpadm.com 4[Date] 3.6 Programs on User Defined Functions 3.6.1 Python User defined function to convert temperature from c to f Steps Define function convert_temp & implement formula f=1.8*c +32 Read temperature in c Call function convert_temp & pass parameter c Print result as temperature in fahrenheit Code def convert_temp(c): f= 1.8*c + 32 return f c= float(input("Enter Temperature in C: ")) f= convert_temp(c) print("Temperature in Fahrenheit: ",f) Output Enter Temperature in C: 37 Temperature in Fahrenheit: 98.60 In above code, we are taking the input from user, user enters the temperature in Celsius and the function convert_temp converts the entered value into Fahrenheit using the conversion formula 1.8*c + 32 3.6.2 Python User defined function to find max, min, average of given list In this program, function takes a list as input and return number as output. Steps Define max_list, min_list, avg_list functions, each takes list as parameter
  • 5. Digitalpadm.com 5[Date] Initialize list lst with 10 numbers Call these functions and print max, min and avg values Code def max_list(lst): maxnum=0 for x in lst: if x>maxnum: maxnum=x return maxnum def min_list(lst): minnum=1000 # max value for x in lst: if x<minnum: minnum=x return minnum def avg_list(lst): return sum(lst) / len(lst) # main function lst = [52, 29, 155, 341, 357, 230, 282, 899] maxnum = max_list(lst) minnum = min_list(lst) avgnum = avg_list(lst) print("Max of the list =", maxnum) print("Min of the list =", minnum) print("Avg of the list =", avgnum) Output Max of the list = 899 Min of the list = 29 Avg of the list = 293.125 3.6.3 Python User defined function to print the Fibonacci series In this program, function takes a number as input and return list as output. In mathematics, the Fibonacci numbers are the numbers in the sequence such as for each number is the sum of its previous two numbers.
  • 6. Digitalpadm.com 6[Date] Following is the example of Fibonacci series up to 6 Terms 1, 1, 2, 3, 5, 8 The sequence Fn of Fibonacci numbers is recursively represented as Fn-1 + Fn-2. Implement function to return Fibonacci series. Code def fiboseries(n): # return Fibonacci series up to n result = [] a= 1 b=0 cnt=1 c=0 while cnt <=n: c=a+b result.append(c) a=b b=c cnt=cnt+1 return result terms=int(input("Enter No. of Terms: ")) result=fiboseries(terms) print(result) Output Enter No. of Terms: 8 [1, 1, 2, 3, 5, 8, 13, 21] Enter No. of Terms: 10 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55] In code above, fiboseries function is implemented which takes numbers of terms as parameters and returns the fibonacci series as an output list. Initialize the empty list, find each fibonacci term and append to the list. Then return list as output 3.6.4 Python User defined function to reverse a String without using Recursion In this program, function takes a string as input and returns reverse string as output.
  • 7. Digitalpadm.com 7[Date] Steps Implement reverse_string function , Use string slicing to reverse the string. Take a string as Input Call reverse_function & pass string Print the reversed string. Code def reverse_string(str): return str[::-1] nm=input("Enter a string: ") result=reverse_string(nm) print("Reverse of the string is: ", result) Output Enter a string: Soft Reverse of the string is: tfoS In this code, one line reverse_string is implemented which takes string as parameter and returns string slice as whole from last character. -1 is a negative index which gives the last character. Result variable holds the return value of the function and prints it on screen. 3.6.5 Python User defined function to find the Sum of Digits in a Number Steps Implement function sumdigit takes number as parameter Input a Number n Call function sumdigit Print result Code def sumdigit(n): sumnum = 0 while (n != 0):
  • 8. Digitalpadm.com 8[Date] sumnum = sumnum + int(n % 10) n = int(n/10) return sumnum # main function n = int(input("Enter number: ")) result=sumdigit(n) print("Result= ",result) Output Enter number: 5965 Result= 25 Enter number: 1245 Result= 12 In this code, Input number n, pass to sumdigit function, sum of digit of given number is computed using mod operator (%). Mod a given number by 10 and add to the sum variable. Then divide the number n by 10 to reduce the number. If number n is non zero then repeat the same steps. 3.6.6 Python Program to Reverse a String using Recursion Steps Implement recursive function fibo which takes n terms Input number of terms n Call function fibo & pass tems Print result Code def fibo(n): if n <= 1: return 1
  • 9. Digitalpadm.com 9[Date] else: return(fibo(n-1) + fibo(n-2)) terms = int(input("Enter number of terms: ")) print("Fibonacci sequence:") for i in range(terms): print(fibo(i),end="") Output Enter number of terms: 8 Fibonacci sequence: 1 1 2 3 5 8 13 21 In above code, fibo function is implemented using a recursive function, here n<=1 is terminating condition, if true the return 1 and stops the recursive function. If false return sum of call of previous two numbers. fibo function is called from the main function for each term. 3.6.7 Python Program to Find the Power of a Number using recursion InpuSteps t base and exp value call recursive function findpower with parameter base & exp return base number when the power is 1 If power is not 1, return base*findpower(base,exp-1) Print the result. Code def findpower(base,exp): if(exp==1): return(base) else: return(base*findpower(base,exp-1)) base=int(input("Enter base: ")) exp=int(input("Enter exp: ")) print("Result: ",findpower(base,exp))
  • 10. Digitalpadm.com 10[Date] Output Enter base: 7 Enter exp: 3 Result: 343 In this code, findpower is a recursive function which takes base and exp as numeric parameters. Here expt==1 is the terminating condition, if this true then return the base value. If terminating condition is not true then multiply base value with decrement exp value and call same function