current position:Home>Python notes - Day9 - higher order functions

Python notes - Day9 - higher order functions

2022-05-15 06:03:17Wandering mage 12

Preface
python Grammar learning , Leave it to those who need it , Understand everything !!

# coding=utf8
# @time:2022/4/15 15:04
# Author  Haoyu 

# 1. Functions are variables 
# python Define function in , Is to define the type as function The variable of , The function name is the variable 
'''''''''
a=10
b=lambda x:x*2
c={
    'a':1,'b':2}
print(type(a),type(b),type(c))  # <class 'int'> <class 'function'> <class 'dict'>
'''''''''

# 1) One variable can assign a value to another variable 
import time

'''''''''
x=100
y=x
print(y+100)
'''''''''

# 2) Change the value of the variable 
# 3) Variables as elements of a sequence 
'''''''''
x=100
list1=[x,200]
print(list1)
'''''''''
# 4) Variables as arguments to functions 
# 5) Variable as the return value of the function 
'''''''''
def func3():
    def s():
        print(' I'm a small function ')
    return s
func3()()
'''''''''

'''''''''
#  practice :
list3 = []
for i in range(5):
    list3.append(lambda x:x*i)
print(list3[1](2))  # 8
print(list3[2](2))  # 8
'''''''''





# 2. Real argument higher order function 
#  A function whose parameter is a function is a higher-order function with real parameters 
'''''''''
# func1 It's a higher-order function with real parameters 
def func1(x):
    print(x())


def func2(m=10):
    print(' Hello ')

func1(func2)
'''''''''










# 3. The use of common higher-order functions in the system 
# max、min、sorted、map、reduce
# max( Sequence ) -  Compare the size of the elements in the sequence to get the element with the largest value 
'''''''''
# 1)max、min
nums = [23,34,65,4,43,234,12]
print(max(nums))    -   # 234
'''''''''
# max( Sequence ,key= function ) -  The function determines the comparison object when the maximum value of the area 
#  Parameters key The requirements of :a. It's a function 
# b. This function has one and only one parameter ( This parameter points to the elements in the sequence )
# c. Function should have a return value ( Comparison object )
'''''''''
# 2)max、min
nums = [23,34,65,4,43,234,12]
def f1(item):
    return item%10
result = max(nums,key=f1)
print(result)
'''''''''

'''''''''
#  Please say that there are the students with the highest scores among the students ?
students=[
    {
    'name':' Xiao Ming ','age':'27','score':'90'},
    {
    'name':' Xiaohong ','age':'53','score':'80'},
    {
    'name':' Little green ','age':'27','score':'70'},
    {
    'name':' The small white ','age':'22','score':'40'},
]
# def f2(item):
# return item['score']
# print(max(students,key=f2)) # {'name': ' Xiao Ming ', 'age': '27', 'score': '90'}

print(max(students,key=lambda item:item['score']))  #{'name': ' Xiao Ming ', 'age': '27', 'score': '90'}
'''''''''
'''''''''
#  Ask the youngest of all students ?
students=[
    {
    'name':' Xiao Ming ','age':'27','score':'90'},
    {
    'name':' Xiaohong ','age':'53','score':'80'},
    {
    'name':' Little green ','age':'27','score':'70'},
    {
    'name':' The small white ','age':'22','score':'40'},
]
# def f3(item):
# return item['age']
# print(min(students,key=f3))
print(min(students,key=lambda item:item['age']))
'''''''''
'''''''''
#  practice : Gets the largest element of the sum of each digit in the list ?
# nums=[23,78,80,72,233,91]
# 5,15,8,9,8,10 -> 78

nums=[23,78,80,72,233,91]
def f3(item):
    n=[int(x) for x in str(item)]
    return sum(n)
print(max(nums,key=f3))
'''''''''

# sorted  Sort 
# sorted( Sequence ) -  Compare the size of the elements in the sequence and sort the elements in the sequence from small to large 
# sorted( Sequence ,key= function ) -  The function determines the size of the comparison object when sorting 
#  Function requirements :
# a. It's a function 
# b. This function has one and only one parameter ( This parameter points to the elements in the sequence )
# c. Function should have a return value ( Comparison object )

'''''''''
#  practice 1: Let the elements in the list be sorted from small to large according to the size of single digits 
nums=[23,78,80,72,26,91]
def f4(item):
    return item%10
print(sorted(nums,key=f4))
'''''''''

# map
'''''''''
 Use a : The original sequence  ->  New sequence 
map( function , Sequence )  -    Convert the sequence in the specified way , The return value is one map object (map The object is a sequence )
 function :a. There is a parameter ( Point to the element in the original sequence )  b. A return value is required ( Elements in the new sequence )
 give an example :
nums = [19,78,76,55,30,12]
result = map(lambda item:item%10,nums)
print(list(result))

 Use two :
map( function , Sequence 1, Sequence 2) -    According to the sequence 1 And sequence 2 Create a new sequence 
 function :a. There are two parameters , Point to the elements in the sequence respectively     b. A return value is required ( Elements in the new sequence )
 give an example :
a = [19,78,76,55,30,12]
b = [19,72,72,55,30,12]
result = map(lambda i1,i2:i1+i2,a,b)
print(list(result))
'''''''''

# reduce  Accumulate all the data in the sequence 
# from functools import reduce  Need to import module 
'''''''''
reduce( function , Sequence , Initial value )
 Function requirements :a. Two parameters are required 
           The first parameter  -    Point to the initial value for the first time ; From the second time, it will point to the result of the previous operation 
           The second parameter  -    Point to each element in the sequence 
          b. A return value is required ( Determine the operation rules )
#  practice 1: Cumulative sum ?
from functools import reduce
nums = [19,78,76,55,30,12]
result = reduce(lambda x,item:x+item,nums,0)
print(result)   # 270

#  function (0,19) -> 0+19=19
#  function (19,78) -> 19+78=97
# ............
#  function (258,12) -> 270
--------------------------------------------
#  practice 2: Cumulative multiplication ?
from functools import reduce
nums = [19,78,76,55,30,12]
result = reduce(lambda x,item:x*item,nums,1)
print(result)   # 2230113600
----------------------------------------------
#  practice 3: Put all the elements in the sequence together ?
# nums = [19,78,76,55,30,12] -> 197876553012
from functools import reduce
nums = [19,78,76,55,30,12]
result = reduce(lambda x,item:x+str(item),nums,'')
print(result)    # 197876553012

'''''''''










# 4. No reference decorator 
# 1) What is a decorator 
'''''''''
 effect : Decorators are used to add functions to functions 
 The essence : It's just a function ( Real argument higher order function + Return value higher order function + Sugar grammar )
 usage ( tricks ):
def  Function name 1( Parameters 1):
    def  Function name 2(*args,**kwarg):
         Code of new functions 
         The code that calls the original function : Parameters 1(*args,**kwarg)
    return  Function name 2
    
 explain :
a. Function name 1  -    Name of decorator , More new features to name 
b. Parameters 1   -    Functions that need to add functions ( Primitive function ), General naming process f、fn
c. Function name 2  -    New function name after adding function ,new_f、new_fn
d.
e.
'''''''''

#  Add the function of counting the execution time of the function to the function 
#  Method 1 : Code for adding functions to functions that need to be added 
#  The problem is : If you add the same function to different functions , The same function needs to be added many times 
'''''''''
def func1():
    star = time.time()
    time.sleep(1)
    print(' function 1 The function of ')
    end = time.time()
    print(' The execution time is :',end-star)
def func2(x,y):
    print(x+y)

func1()
func2(10,20)

'''''''''
#  Method 2 : Encapsulate the functions to be added into a function 
#  Existing problems : The original function has no new functions 
'''''''''
def func3():
    print(' Hello world ')


def count_time(f):
    #  Get start time 
    star = time.time()
    #  Call the original function 
    time.sleep(1)
    f()
    #  Get the end time 
    end = time.time()
    #  Calculate the time difference 
    print(' The execution time is :',end-star)

count_time(func3)
'''''''''

#  Method 3 : Decorator 
'''''''''
 usage ( tricks ):
def  Function name 1( Parameters 1):
    def  Function name 2():
         Code of new functions 
         The code that calls the original function : Parameters 1()
    return  Function name 2

 explain :
a. Function name 1 -  Name of decorator , More new features to name 
b. Parameters 1 -  Functions that need to add functions ( Primitive function ), General naming process f、fn
c. Function name 2 -  New function name after adding function ,new_f、new_fn


def count_time(f):
    def new_fn(*args,**kwarg):
        start = time.time()
        time.sleep(1)
        f(*args,**kwarg)
        end = time.time()
        print(' The execution time is :', end - start)
    return new_fn()

@count_time
def func5():
    print(' Hello python')
func5       #  Hello python  The execution time is : 1.0091712474822998
'''''''''

'''''''''
#  practice : Write a decorator , Open... When the function starts executing ‘start’
def zz(f):
    def new_f(*args,**kwargs):
        print('start')
        f(*args,**kwargs)
    return new_f

@zz
def func6():
    print('Hello World')

@zz
def func7(x,y):
    print(x+y)


func7(10,20)
func6()
#  Output :
start
30
start
Hello World
'''''''''









# 5. There are ornaments for reference 
#  Application scenarios : If you need additional data to realize the function of decorator , You need a reference decorator 
'''''''''
def  Function name ( parameter list )
     Define parameterless decorator functions 
    return  Parameterless decorator function name 

 Function name : The name of the function that created the decorator 

#  Example : Write a reference decorator , Add a label 
def create_tag(name):
    def tag(f):
        def new_f(*args,**kwargs):
            result=f(*args,**kwargs)
            return f'<{name}>{result}</name>'
        return new_f
    return tag

@create_tag('a')
def func1():
    return 'hello'
print(func1())
'''''''''

More secure sharing , Please pay attention to 【 Security info】 WeChat official account !

copyright notice
author[Wandering mage 12],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/131/202205110607424568.html

Random recommended