day12 function advanced

day12 function advanced

1. Anonymous function

(1) Anonymous function
  • Syntax: function name = lambda parameter list: return value

  • Equivalent to: def function name (parameter list)

    Return return value

  • Note: anonymous functions can only implement functions that can be completed in one sentence of code

    Anonymous functions are no different from ordinary functions when called

    Arguments to anonymous functions cannot use colon syntax to describe types

sum1 = lambda num1, num2=10: num1 + num2

print(sum1(10, 20))
print(sum1(num1=100, num2=200))
print(sum1(5))
  • Exercise: define an anonymous function to get a specified number of digits
units_digit = lambda num: num % 10
print(units_digit(123))

2. Variable scope

  • Variable scope: refers to the scope within which a variable can be used
  • According to the different scope of variables, variables are divided into global variables and local variables
(1) Global variable
  • Variables not defined in functions or classes are global variables
  • The scope of global variables is from the beginning of definition to the end of the program
(2) Local variable
  • The variables defined in the function are local variables (formal parameters are also local variables)
  • The scope of a local variable is from the beginning of the definition to the end of the function
(3) Function call procedure
  • Every time a function is called, the system will automatically open up a temporary memory area for the function in the stack to store the local variables defined in the function
  • When the function call ends, the system will release this memory by itself
global variable
a = 100

for b in range(10):
    print(b)
    c = 20
    print(f'Use in circulation a:{a}')

print(f'Recycling for external use b and c:{b}, {c}')


def func1():
    print(f'Used in function a,b,c:{a}, {b}, {c}')


func1()
local variable
def func2(x):
    y = 100
    for z in range(10):
        pass
    print('End of function')
    print(f'Used in function x, y, z:{x}, {y}, {z}')\


func2(20)
(4)global and nonlocal
  • Global: to modify the value of a global variable in a function, you need to use global to describe the variable

    To define a global variable in a function, you need to use global to describe the variable

  • global variable name

  • (understand) nonlocal - if you need to modify the value of a local variable locally, you need to use nonlocal for description

m = 100
n = 100


def func3():
    # Instead of modifying the value of the global variable m, a new local variable m is redefined
    m = 200

    global n
    n = 200

    # You can use global variables in functions
    print(f'In function m:{m}')
    print(f'In function n:{n}')

    global x
    x = 'abc'


func3()
print(f'Outside function m:{m}')
print(f'Outside function n:{n}')
print(f'Outside function x:{x}')
ab = 100


def func4():
    xy = 200
    print(f'func4:{ab}, {xy}')

    def func5():
        nonlocal xy
        xy = 300
        print(f'func5:{ab}, {xy}')

    func5()
    print(f'func4-xy:{xy}')


func4()

3. A function is a variable

1. Important conclusions
  • The definition type of function in python is the variable of function, and the function name is the variable name
func1 = lambda x: x*2
print(type(func1))    # <class 'function'>
Equal to:
def func1(x):
    return x*2
def func2():
    print('function!')


a = 10

print(type(a))      # <class 'int'>
print(type(func2))  # <class 'function'>

print(id(a))
print(id(func2))
Variables as arguments to functions
def func3(x):
    print(f'x:{x}')


def func4():
    print('Function 4')


func3(199)

num = 200
func3(num)

func3(func4)
  • x can pass numbers, strings, lists and tuples
def func5(x):
    print(x * 2)
  • x can transfer strings, lists, tuples and dictionaries
def func6(x):
    print(x[0])
  • x can only be transferred to the list
def func7(x):
    x.append(100)
    print(x)
  • func8 and func9 are higher-order functions with arguments - because they have functions in their arguments
  • x can only pass functions, and this function can be called without parameters
def func8(x):
    print(x())
  • x can only transfer function; Only one parameter can be accepted when calling a function; The return value must be a number
def func9(x):
    print(x(10) / 2)
"""func10 Is a higher-order function of return value - because func10 The return value of is a function"""
def func10():
    def func11():
        print('hello')
        return 100
    return func11


"""print(func11())  => print(100)"""
print(func10()())

4. Higher order functions of common real parameters

(1) Common real parameter higher order function
  • max,min,sorted / sort
  • map
  • reduce
"""max,min,sorted
  • Max (sequence, key = function)

  • Function requirements: a. there is and only one parameter (this parameter points to each element in the previous sequence)

    b. there is a return value (the return value is the comparison object)

"""a.seek nums The element with the largest bit in the middle: 89"""
nums = [89, 78, 90, 23, 67, 81]

# Method 1:
"""
def temp(item):
    return item % 10
print(max(nums, key=temp))
"""

# Method 2
print(max(nums, key=lambda item: item % 10))


"""b.seek nums The element with the largest median(Treat string numbers as numbers): '100'"""
nums = [89, '100', 34, '78', 90]
print(max(nums, key=lambda item: int(item)))
"""d. obtain nums The number of bits and the largest element"""
nums = [123, 97, 56, 109, 82]
"""6, 16, 11, 10, 10"""
def temp(item):
    s = 0
    for x in str(item):
        s += int(x)
    return s


print(max(nums, key=temp))
print(sorted(nums, key=temp))

5.map and reduce

(1) map
  • Map (function, sequence): transform all elements in the sequence according to the specified rules to produce a new sequence

  • Function requirements: A. there is a parameter (pointing to the element in the original sequence)

    b. a return value is required (the element in the new sequence, describing the relationship between the new sequence element and the original sequence element)

  • Map (function, sequence 1, sequence 2)

  • Function requirements: a. There are two parameters. The first parameter points to the elements in sequence 1 and the second parameter points to the elements in sequence 2

    b. a return value is required (for the elements in the new sequence, describe the relationship between the new series elements and the original series elements)

  • Function can be followed by N sequences, and the number of elements in these N sequences must be consistent; As many sequences as there are, so many parameters are needed in the function

[23, 45, 78, 91, 56]  -> ['23', '45', '78', '91', '56']
[23, 45, 78, 91, 56]  -> [3, 5, 8, 1, 6]

nums = [23, 45, 78, 91, 56]
print(list(map(lambda item: str(item), nums)))
print(list(map(lambda item: item % 10, nums)))
nums1 = [1, 2, 3, 4, 5]
nums2 = [6, 7, 8, 9, 1]
# [16, 27, 38, 49, 51]
result = map(lambda i1, i2: i1 * 10 + i2, nums1, nums2)
print(list(result))

(2) reduce
  • Reduce (function, sequence, initial value)
  • Function: a. with and only two parameters

The first parameter: point to the initial value for the first time, and point to the previous operation result for the second time (which can be regarded as the initial value)

The second parameter: points to each element in the sequence

b. return value: describes the merge rule (described by initial value and element)

[1, 2, 3, 4, 5]  -> 15 (1+2+3+4+5)   Initial value 0
[1, 2, 3, 4, 5]  -> 120 (1*2*3*4*5)  Initial value 1
[1, 2, 3, 4, 5]  -> '12345'   ('' + '1'+'2'+'3'+'4'+'5')     Initial value ''
from functools import reduce

nums = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x+y, nums, 0)
print(result)

result = reduce(lambda x, y: x * y, nums, 1)
print(result)

result = reduce(lambda x, y: x+str(y), nums, '')
print(result)
  1. What has been saved in the points list is the coordinates of each point (the coordinates are represented by tuples, the first value is the x coordinate, and the second value is the y coordinate)

    points = [
      (10, 20), (0, 100), (20, 30), (-10, 20), (30, -100)
    ]
    

    The following problems are solved using real parameter higher-order functions

    1) Gets the point with the largest y coordinate in the list

    2) Gets the point with the smallest x coordinate in the list

    3) Gets the point furthest from the origin in the list

    4) The points are sorted from large to small according to the distance from the point to the x axis

  2. Find the element with the largest absolute value in the list nums

  3. We have two lists A and B. create A dictionary with the map function. The element in A is key and the element in B is value

    A = ['name', 'age', 'sex']
    B = ['Zhang San', 18, 'female']
    New dictionary: {'name': 'Zhang San', 'age': 18, 'sex': 'female'}
    
  4. The three lists represent the names, subjects and class numbers of five students respectively. Use map to spell the three lists into a dictionary representing each student's class information

    names = ['Xiao Ming', 'floret', 'Xiao Hong', 'Lao Wang']
    nums = ['1906', '1807', '2001', '2004']
    subjects = ['python', 'h5', 'java', 'python']
    result:{'Xiao Ming': 'python1906', 'floret': 'h51807', 'Xiao Hong': 'java2001', 'Lao Wang': 'python2004'}
    
  5. A list message has been created, and reduce is used to calculate the sum of all numbers in the list (using list derivation and not using list derivation)

    message = ['Hello', 20, '30', 5, 6.89, 'hello']
    Result: 31.89
    
  6. It is known that a dictionary list stores the grades of each student in each subject,

    1) Calculate and add the average score of each student

    2) Sort from high to low according to the average score

    studens = [
      {'name': 'stu1', 'math': 97, 'English': 67, 'Chinese': 80},
      {'name': 'stu2', 'math': 56, 'English': 84, 'Chinese': 74},
      {'name': 'stu3', 'math': 92, 'English': 83, 'Chinese': 78},
      {'name': 'stu4', 'math': 62, 'English': 90, 'Chinese': 88}
    ]
    
    # Calculate average score
    studens = [
      {'name': 'stu1', 'math': 97, 'English': 67, 'Chinese': 80, 'avg':81},
      {'name': 'stu2', 'math': 56, 'English': 84, 'Chinese': 74, 'avg':71},
      {'name': 'stu3', 'math': 92, 'English': 83, 'Chinese': 78, 'avg':87},
      {'name': 'stu4', 'math': 62, 'English': 90, 'Chinese': 88, 'avg':80}
    ]
    
    # Sort from high to low according to the average score
    ...
    

Keywords: Python

Added by pakmannen on Mon, 10 Jan 2022 18:06:50 +0200