day12 function advanced

Posted by eerikk2 on Mon, 10 Jan 2022 17:00:35 +0100

Python function advanced

1. Anonymous function

Syntax:
Function name = lambda parameter list: return value

amount to:
def function name (parameter list):
Return return value
be careful:
1) Anonymous functions can only implement functions that can be completed in one sentence of code
2) Anonymous functions are no different from ordinary functions when called
3) 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 - 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 (memory change)
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 automatically release this memory.

"""1.global variable"""
# a. b and c are global variables
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()

"""2. 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)
# print(f'Use outside function x,y,z:{z}')   # report errors

3) global and nonlocal - can only be used in function bodies

global - 1) to modify the value of a global variable in a function, you need to use global to describe the variable;
2) 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()

4) Important conclusion

A function defined in python is a variable whose type is 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))

b = a
print(b + 10)

c = func2
c()

list1 = [a, 100]
list2 = [func2, 100, func2()]
print(list2)

a = 'abc'
func2 = 'abc'

"""1.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()())

3. Higher order functions of common real parameters

1)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)

nums = [89, 78, 90, 23, 67, 81]
print(max(nums))

"""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)))

"""c.Obtain the information of the oldest students; Get information about the students with the lowest grades"""
students = [
    {'name': 'Xiao Ming', 'age': 18, 'score': 90},
    {'name': 'Lao Wang', 'age': 28, 'score': 67},
    {'name': 'Zhang San', 'age': 22, 'score': 83},
    {'name': 'Li Si', 'age': 25, 'score': 57}
]

print(max(students, key=lambda item: item['age']))
print(min(students, key=lambda item: item['score']))

"""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))


# Implementation principle of max (understand)
def yt_max(seq, *, key=None):
    """"""
    """
    seq = [89, 78, 90, 23, 67, 81]
    key = lambda item: item % 10
    """
    if key:
        seq = list(seq)
        m = seq[0]
        for x in seq[1:]:
            if key(x) > key(m):
                m = x
        return m

    else:
        seq = list(seq)
        m = seq[0]
        for x in seq[1:]:
            if x > m:
                m = x
        return m


"""
seq = [89, 78, 90, 23, 67, 81]
m = 89
x = 78, 90, 23, 67, 81
x = 78: if key(78) > key(89)  -> if 8 > 9 -> if False
x = 90: if key(90) > key(89)  -> if 0 > 9  -> if False
"""

nums = [89, 78, 90, 23, 67, 81]
print(yt_max(nums))
print(yt_max(nums, key=lambda item: item % 10))

print(yt_max(students, key=lambda x: x['score']))

2)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 (the element in the new sequence, describing the relationship between the new sequence element and the original sequence element)

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

"""
[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))

"""
practice:
['Xiao Ming', 'Zhang San', 'Li Si', 'Lao Wang']
[18, 30, 26, 35]

->
[
    {'name': 'Xiao Ming', 'age': 18},
    {'name': 'Zhang San', 'age': 30},
    ...
]
"""
names = ['Xiao Ming', 'Zhang San', 'Li Si', 'Lao Wang']
ages = [18, 30, 26, 35]
result = map(lambda i1, i2: {'name': i1, 'age': i2}, names, ages)
print(list(result))

3)reduce

Reduce (function, sequence, initial value)
Function: a. with and only two parameters
The first parameter: points to the initial value for the first time, and points to the previous operation result for the second time (which can be directly 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 values and elements)

from functools import reduce
"""
[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 ''

"""

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)

"""
students = [
    {'name': 'Xiao Ming', 'age': 18, 'score': 90},
    {'name': 'Lao Wang', 'age': 28, 'score': 67},
    {'name': 'Zhang San', 'age': 22, 'score': 83},
    {'name': 'Li Si', 'age': 25, 'score': 57}
]

Requirement 1:'Xiao Ming Lao Wang Zhang San Li Si'
'' + 'Xiao Ming' + 'Lao Wang' + 'Zhang San' + ...

Requirement 2:['Xiao Ming', 'Lao Wang', 'Zhang San', 'Li Si']
[] + ['Xiao Ming'] + ['Lao Wang'] + ...
"""
students = [
    {'name': 'Xiao Ming', 'age': 18, 'score': 90},
    {'name': 'Lao Wang', 'age': 28, 'score': 67},
    {'name': 'Zhang San', 'age': 22, 'score': 83},
    {'name': 'Li Si', 'age': 25, 'score': 57}
]

result = reduce(lambda x, y: x + y['name'], students, '')
print(result)

result = reduce(lambda x, y: x + [y['name']], students, [])
print(result)

Job:

  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

    points = [(10, 20), (0, 100), (20, 30), (-10, 20), (30, -100)]
    result = max(points, key=lambda y: y[-1])
    print(result)
    

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

    points = [(10, 20), (0, 100), (20, 30), (-10, 20), (30, -100)]
    result = min(points, key=lambda x: x[0])
    print(result)
    

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

    points = [(10, 20), (0, 100), (20, 30), (-10, 20), (30, -100)]
    result = max(points, key=lambda xy: xy[0] ** 2 + xy[-1] ** 2)
    print(result)
    

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

    points = [(10, 20), (0, 100), (20, 30), (-10, 20), (30, -100)]
    result = sorted(points, key=lambda x: x[0], reverse=True)
    print(result)
    
  2. Find the element with the largest absolute value in the list nums

    nums = [-2, 5, 15, -10]
    result = max(nums, key=lambda x: int((x ** 2) ** 0.5))
    print(result)
    
  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'}
    
    A = ['name', 'age', 'sex']
    B = ['Zhang San', 18, 'female']
    result = map(lambda key1, value1: (key1, value1), A, B)
    print(dict(result))
    
  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'}
    
    names = ['Xiao Ming', 'floret', 'Xiao Hong', 'Lao Wang']
    nums = ['1906', '1807', '2001', '2004']
    subjects = ['python', 'h5', 'java', 'python']
    result = map(lambda name1, num1, subject1: (name1, subject1 + num1), names, nums, subjects)
    print(dict(result))
    
  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
    
    message = ['Hello', 20, '30', 5, 6.89, 'hello']
    from functools import reduce
    
    # Use reduce
    result = reduce(lambda x, y: x + (y if type(y) == int or type(y) == float else 0), message, 0)
    print(result)
    
    # List derivation:
    num1 = [x for x in message if type(x) == int or type(x) == float]
    print(sum(num1))
    
  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
    ...
    
    # 1) Calculate and add the average score of each student
    print('---------------6.1--------------------')
    result = list(map(lambda y: {'name': y['name'], 'math': y['math'], 'English': y['English'], 'Chinese': y['Chinese'], 'avg': int((y['math'] + y['English'] + y['Chinese']) / 3)}, students))
    print(result)
    # Calculate average score
    students = [
        {'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': 84},
        {'name': 'stu4', 'math': 62, 'English': 90, 'Chinese': 88, 'avg': 80}
    ]
    # 2) Sort from high to low according to the average score
    print('---------------6.2--------------------')
    print(sorted(students, key=lambda item: item['avg'], reverse=True))
    

Topics: Python Programmer