Posted by zavin on Tue, 01 Mar 2022 13:00:51 +0100

### 1. Anonymous function

The essence of anonymous functions is still functions. They have different syntax for definition, and everything else is the same
Note: anonymity can only be used to implement functions with very simple functions

Syntax:
Function name = lambda parameter list: return value

Convert to normal:
def function name (formal parameter list):
Return return value

```# Exercise: write an anonymous function to judge whether the specified number is even. If so, return True, otherwise return False
bool1 = lambda num1: num1 % 2 == 0
print(bool1(20))

# Exercise 2: write an anonymous function to judge whether the specified year is a leap year. If so, return True; otherwise, return False
bool1 = lambda num1: (num1 % 4 == 0 and num1 % 100 != 0) or num1 % 400 == 0
print(bool1(2024))
```

### 2. Scope of variable

##### 1. Scope of variable

Variable defines the range that can be used later
According to the scope of variables, they are divided into global variables and local variables

##### 2. Global and local variables

"""
1) Global variable
Variables not defined in functions and classes are global variables;
The scope of global variables is from the beginning of definition to the end of the program
Global variables are stored in the global stack interval, which will not be released automatically until the program is finished

2) Local variable
The variables defined in the function are local variables, including formal parameters
The scope of a local variable is from the beginning of the definition to the end of the function

When calling a function, the system will automatically create a temporary stack interval for the function to save the data generated in the function (including local variables),
When the function call ends, the temporary stack interval will be released automatically.
"""

##### 3.global keyword
```def func5():
# Instead of modifying the value of the global variable m, a global variable value is created in the function
m = 200
print(f'm2:{m}')

# Function 1: modify the value of a global variable in the function. Before modifying, use global to describe the variable
global n
n = 200
print(f'n:{n}')

# Function 2: define a global variable in the function
global p
p = 300

func5()
print(m)
print(n)
print(p)
```

### 3. A function is a variable

##### 1. Defining a function in python is actually defining a variable whose type is function, and the function name is the variable name

Variables and functions can do anything

##### 2. High order function: real parameter high order function and return value high order function

1) Real parameter higher order function

```def func1(x):
# x = t
x(10, 20, 30) * 2

def t(a, b, c):
print('Function!')
return 100

func1(t)
```

2) Higher order function of return value

```def func2():
def func3():
return 'abc'
return func3()

func2()  # func3()  -  'abc'
```

### 4. Real parameter higher-order function

Higher order functions of common parameters: max, min, sorted(sort), map, reduce

##### 1. If the parameter of the function is the way the function provides arguments: a. use the function name of the ordinary function, b. use the anonymous function
```def func1(x):
print(x(10) + 2)

# Requirement of x: it is a function; Function has one parameter; The return value of the function is a number
def t(x):
return x*2
func1(t)
```
##### 2. Higher order functions of common real parameters

1)max, min, sorted, list sort

```"""
max(sequence)  -  Find the element with the largest value in the sequence
max(sequence, key=function)  -  Gets the largest element in the sequence according to the rule specified by the function
Function requirements: 1)With and only one parameter(This parameter represents the elements in the sequence)
2)There is a return value(Comparison object)

min(sequence, key=function)  -  Gets the smallest element in the sequence according to the rule specified by the function
sored(sequence, key=function)  -  Sort the elements in the sequence from small to large according to the rules specified by the function
list.sort(sequence, key=function)  -
"""
```
```# Gets the element with the largest value in num
nums = [29, 73, 64, 31, 55, 76]
print(max(nums, key=lambda item: item))

# Exercise 1: get the element with the largest sum of single digits in nums
nums = [29, 73, 64, 68, 31, 55, 766]
print(max(nums, key=lambda item: sum([int(x) for x in str(item)])))

# Exercise 3: get the element with the largest absolute value in nums
nums = [29, 73, 64, -31, 68, 55, -76]
print(max(nums, key=lambda item: item*-1 if item < 0 else item))

# Exercise 4: get the element with the largest y coordinate in points
points = [(19, 2), (0, 18), (3, 4)]
print(max(points, key=lambda item: item[1]))

# Exercise 5: get the oldest students; Students with the highest scores
students = [
{'name': 'stu1', 'age': 19, 'score': 72},
{'name': 'stu2', 'age': 22, 'score': 89},
{'name': 'stu3', 'age': 30, 'score': 60},
{'name': 'stu4', 'age': 17, 'score': 77}
]
print(max(students, key=lambda item: item['score']))
```

2)map - transform the elements in the sequence according to the rules specified by the function to get a new sequence

```"""
map(function, sequence)
Function requirements:1.With and only one parameter(Represents the elements in the sequence)
2.There is a return value(Elements in the new sequence - In this, we only need to describe the relationship between the elements in the new sequence and the elements in the original sequence)

map(function, Sequence 1, Sequence 2)
Function requirements:1.With and only one parameter(Represents the elements in the sequence)
2.There is a return value(Elements in the new sequence - In this, we only need to describe the relationship between the elements in the new sequence and the elements in the original sequence)

map(function, Sequence 1, Sequence 2, ...)
"""
```
```# Exercise 2: multiply all elements in nums by 2
nums = [29, 73, 64, 301, 68, 55, 76]
# [58, 146, 128, 602, 136, 110, 152]
result = list(map(lambda item: item*2, nums))
print(result)

# Exercise 4:
nums1 = [238, 89, 78, 23]
nums2 = [92, 78, 61, 44]
# [82, 98, 81, 34]
result = list(map(lambda item, item2: item % 10 * 10 + item2 % 10, nums1, nums2))
print(result)

# Exercise 5
list1 = ['python', 'java', 'h5']
list2 = [22, 21, 19]
list3 = [2, 9, 18]
# ['python2202', 'java2109', 'h51918']
result = list(map(lambda item1, item2, item3: f'{item1}{item2}{item3:0>2}', list1, list2, list3))
print(result)
```

3)reduce - merge the elements in the sequence into one data according to the specified rules

```"""
reduce(function, sequence, Initial value)
Initial value:Usually 0, 1 or empty string
Function requirements:1.With and only two parameters(The first parameter points to the initial value;The second parameter points to each element in the sequence)
2.There is a return value(Decide how to merge)

be careful: use reduce You must start from functools Import in module
"""
```
```from functools import reduce

nums = [10, 23, 4, 8]
# Sum all elements
result = reduce(lambda x, item: x + item, nums, 0)
print(result)

nums = [10, 23, 4, 8]
# Find the product of all elements: 10x23x4x8
result = reduce(lambda x, item: x * item, nums, 1)
print(result)

students = [
{'name': 'stu1', 'age': 19, 'score': 72},
{'name': 'stu2', 'age': 22, 'score': 89},
{'name': 'stu3', 'age': 30, 'score': 60},
{'name': 'stu4', 'age': 17, 'score': 77}
]
# Total score
result = reduce(lambda x, item: x + item['score'], students, 0)
print(result)
```

1. Write an anonymous function to judge whether the specified year is a leap year

```bool1 = lambda num1: (num1 % 4 == 0 and num1 % 100 != 0) or num1 % 400 == 0
print(bool1(2024))
```
2. Write a function to reverse the order of elements in a specified list (such as [1, 2, 3] - [3, 2, 1]) (Note: do not use the reverse order function of the list)

```a1 = lambda item: item[::-1]
print(a1([1, 2, 3]))
```
3. Write a function to calculate the sum of squares of the bits of an integer

```for example: sum1(12) -> 5(1 Square of plus square of 2)    sum1(123) -> 14
```
```def sum1(nums):
result = 0
nums2 = str(nums)
for x in nums2:
result += int(x)**2
return result

print(sum1(12))

nums = 12
result = int(reduce(lambda x, item: x + int(item)**2, str(nums), 0))
print(result)
```
1. Find the element with the smallest absolute value in the list nums
```For example: nums = [-23, 100, 89, -56, -234, 123], The maximum value is:-23
```
```nums = [29, 73, 64, -31, 68, 55, -76]
print(min(nums, key=lambda item: item*-1 if item < 0 else item))
```
1. 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']
print(dict(map(lambda item, item2: (item, item2), A, B)))

```
2. 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 the class information of each student

```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']
subjects = ['python', 'h5', 'java', 'python']
nums = ['1906', '1807', '2001', '2004']
print(dict(map(lambda item, item2, item3: (item, item2 + item3), names, subjects,nums)))
```
3. A list message has been created. Use reduce to calculate the sum of all numbers in the list

```message = ['Hello', 20, '30', 5, 6.89, 'hello']
Result: 31.89
```
```message = ['Hello', 20, '30', 5, 6.89, 'hello']
print(reduce(lambda x, item: x + (item if type(item) in (int, float) else 0), message, 0))
```
4. 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)
]
```

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

```print(max(points, key=lambda item: item[-1]))
```

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

```print(min(points, key=lambda item: item[0]))
```

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

```print(max(points, key=lambda item: (item[0]**2 + item[-1]**2) / 2))
```

4) Sort the points according to the distance from the point to the x-axis from large to small

```points = [
(10, 20), (0, 100), (20, 30), (-10, 20), (30, -100)
]
print(sorted(points, key=lambda item: item[0] if item[0] > 0 else item[0] * -1, reverse=True))
```

Topics: Python