Advanced Function Concepts in Python

栏目: IT技术 · 发布时间: 4年前

内容简介:The usage of functions in your program improves the simplicity of code and made the debugging simple. Python gives wonderful control over creating and utilizing functions in your programs. In the previous article, I have clearly explained the process of cr

The usage of functions in your program improves the simplicity of code and made the debugging simple. Python gives wonderful control over creating and utilizing functions in your programs. In the previous article, I have clearly explained the process of creating a function. In this,we will learn about some advanced functional programming concepts in python. Once you mastered these things you can write better programs than before. Let me try to explain everything in simple manner as much as possible. On successful completion of this reading, you can create functions in one line of code, you can create iterators from the given sequences.

Lambda Expressions

Lambda is a pure anonymous function in python which allows us to write a function in a single line of code. It reduces the effort of programmer in writing multiple lines of code to create user defined functions. Before going to write the actual code we must understand the concept behind the lambda function. Look at the explanation about lambda in Wikipedia .

Lambda calculus(also written as λ- calculus ) is a formal system in mathematical logic for expressing computation based on function abstraction and application using variable binding and substitution. It is a universal model of computation that can be used to simulate any Turing machine.

Lambda Function Symbol

Lambda calculus was introduced by the mathematician Alonzo Church to investigate about the foundational mathematical calculus. This calculus helps the mathematicians to understand the mechanism between basic arithmetic and logical operations. The symbolic representation of the lambda is λ Greek alphabet.

In python the function is denoted with the keyword lambda . Look at the syntax of the lambda function.

Syntax: lambda arguments : expression

Let us create a function to calculate the volume of given cube.

def volume(side):
    return side*side*sideside = int(input("Enter Side of Cube"))
Volume_of_cube = volume(side)
print( Volume_of_cube ) 

Look at the following code which contains lambda expression to create the function.

side = int(input("Enter Side of Cube"))
Volume_of_cube = lambda side : side * side * sideprint( Volume_of_cube (side) )

The both codes gives the same output for similar kind of inputs as follows.

Enter Side of Cube6
216

Why Anonymous?

In the previous program we have called the lambda function with the help of the name Volume_of_cube . But actually this name is not a function name. The previous program is just one of the way to use lambda function. In python the function created using the lambda does not have any function name. In the program the variable name itself acted as function name. To understand clearly you can replace the entire lambda expression instead of the variable name.

side = int(input("Enter Side of Cube")) 
print( (lambda side : side * side * side) (side) )

I hope you can understand the concept. That is why the lambda expression is called as anonymous function. There are certain conditions in creating lambda function in Python. More than one argument can be passed in the lambda expression but only one expression can be created in it. Some more examples are given below using lambda functions.

add = lambda a,b,c : a + b + c
print( add(5,4,6) )multiply = lambda x,y : x * y
print( multiply(3,7) )power = lambda m,n : m ** n
print( power(6,2) )

Output

Map function in Python

Map is a function used to trace the sequencing objects. The map function reduces great effort of applying some functions for each elements of collections such as list and dictionaries. Let us try to get a list of interest amount of each employee for an particular sum of money using normal way.

Photo by Honey Yanibel Minaya Cruz on Unsplash

Syntax: map[]

def interest(amount, rate, year):
    return amount * rate * year / 100amount = [10000, 12000, 15000]
rate = 5
year = 3for x in amount:
    y = interest(x, rate, year)
    print(y)

Output

1500.0
1800.0
2250.0

The same can be done easily with the help of map function in Python. The following code is created using the map function.

def interest(amount):
    rate = 5
    year = 3    
    return amount * rate * year / 100amount = [10000, 12000, 15000]interest_list = map(interest,amount)
print( interest_list )

Output

<map object at 0x7fd6e45d90b8>

Get confused with the output? The map function always return a map object. We have type cast the object using list keyword.

def interest(amount):
    rate = 5
    year = 3    
    return amount * rate * year / 100amount = [10000, 12000, 15000]interest_list = list( map(interest,amount) )
print( interest_list )

Output

[1500.0, 1800.0, 2250.0]

Map function is not only take the user defined function. We can use the built in function also.

name = ["alex", "felix", "antony"]
cap = list( map(str.capitalize, name))
print(cap) 

Output

['Alex', 'Felix', 'Antony']

Filter Function in Python

In some times you have to filter some elements in a list based on some conditions. Let us consider a list of ages of ten persons. We have to filter the persons based on their age. If a person’s age is greater than or equal to 24 then they can be eligible to be in the list. In a normal way, we can use something like the following.

list_of_age = [10, 24, 27, 33, 30, 18, 17, 21, 26, 25]filtered_list = []for x in list_of_age:
    if(x>=24):
        filtered_list.append(x)print( filtered_list )

Using filter function this can be very easy. The filter function returns an object that contains the elements that are true for certain conditions.

Syntax:filter(function, iterables)

def eligibility(age):
    if(age>=24):
        return True
list_of_age = [10, 24, 27, 33, 30, 18, 17, 21, 26, 25]age = filter(eligibility, list_of_age)print(list(age))

The output for the previous programs are given below.

[24, 27, 33, 30, 26, 25]

Reduce function in Python

Reduce is a built in function in a module called functools. It reduces the size of iterable objects by applying function in each step. The syntax of reduce() function is given below.

Syntax:reduce(function, iterables, start)

Let us consider a list of five numbers [1, 2, 3, 4, 5] from which you need to find the sum of the numbers. The reduce function first takes the numbers (1,2) then pass them through the defined function. Then the return value from the first one and the third value will be passed through the function. Let the name of the function be add() then the steps involved in finding the sum will be the following.

add(1, 2) 
add(add(1, 2) , 3)
add(add(add(1, 2) , 3), 4)
add(add(add(add(1, 2) , 3), 4),5)

The actual code for the previous explanation is given below.

from functools import reduce
def add(a,b):
    return a+b
list = [1, 2, 3, 4, 5]
sum = reduce(add, list)
print(list(sum))

Output

Combining Lambda with Map, Filter and Reduce

The higher order functions can replace the function object with the lambda expressions. The usage of lambda expression helps us to implement the discussed concept easily with a couple of lines of code.

Lambda with Map

The following code will help you to know how to implement the map function with lambda. Let us try to create a list of power of a list.

list_of_numbers = [10, 6, 5, 17, 15]
order = 2
power = map(lambda x : x ** order, list_of_numbers)
print(list(power))

Output

[100, 36, 25, 289, 225]

Lambda with Filter

The conditional statements can be used with lambda expressions. Using the return value from the lambda function we can use filter the list.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even = list(filter(lambda x: x%2==0, numbers))
print(even)

Output

[2, 4, 6, 8, 10]

I hope this article helped you to understand some interesting concepts in functional programming. Practice more using the concepts explained in this article.

Happy coding!


以上所述就是小编给大家介绍的《Advanced Function Concepts in Python》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

腾讯网UED体验设计之旅

腾讯网UED体验设计之旅

任婕 等 / 电子工业出版社 / 2015-4 / 99.00元

《腾讯网UED体验设计之旅》是腾讯网UED的十年精华输出,涵盖了丰富的案例、极富冲击力的图片,以及来自腾讯网的一手经验,通过还原一系列真实案例的幕后设计故事,从用户研究、创意剖析、绘制方法、项目管理等实体案例出发,带领读者经历一场体验设计之旅。、 全书核心内容涉及网媒用户分析与研究方法、门户网站未来体验设计、H5技术在移动端打开的触控世界、手绘原创设计、改版迭代方法、文字及信息图形化设计、媒......一起来看看 《腾讯网UED体验设计之旅》 这本书的介绍吧!

JSON 在线解析
JSON 在线解析

在线 JSON 格式化工具

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具