# day13 built in functions and Derivations Today's summary:

• Anonymous function
• generator
• Built in function
• Additional: derivation, which belongs to the knowledge of data type. The internal advanced usage will involve the knowledge of [generator] and [function].

## 1. Anonymous function

The traditional definition of function includes: function name + function body.

Famous functions are operated by function names as follows:

```def send_email():
pass

# 1. Implementation
send_email()
# 2. As a list element
data_list = [send_email, send_email, send_email ]
# 3. Pass as parameter
other_function(send_email)
```

Anonymous functions are defined based on lambda expression implementation, and can have no name, for example:

```data_list = [ lambda x:x+100,  lambda x:x+110, lambda x:x+120 ]

print( data_list )
```
```f1 = lambda x:x+100

res = f1(100)
print(res)
```

The function format defined based on lambda is: lambda parameter: function body

• Parameter. Any parameter is supported.

```lambda x: Function body
lambda x1,x2: Function body
lambda *args, **kwargs: Function body
```
• Function body can only support single line code.

```def xxx(x):
return x + 100

lambda x: x + 100
```
• Return value. By default, the result of single line code execution in the function body is returned to the executor of the function.

```func = lambda x: x + 100

v1 = func(10)
print(v1) # 110
```

Comparison:

```# Traditional writing:
def func(a1,a2):
return a1 + a2 + 100
#Anonymous function can only be written in a single line
foo = lambda a1,a2: a1 + a2 + 100
```

Anonymous functions are suitable for simple business processing and can create functions quickly and simply.

### Exercises

Write the expression of its anonymous function according to the function

```def func(a1,a2):
return a1 + a2

func = lambda a1,a2: a1+a2
```
```def func(data):
return data.replace("Aoi Sora","***")

func= lambda data: data.replace("Aoi Sora","***")
```
```def func(data):
name_list = data.replace(".")
return name_list[-1]

func = lambda data: data.replace(".")[-1]
```

When writing anonymous functions, because the restricted function body can only write one line, anonymous functions can only handle very simple functions.

### Extensions: ternary operations

Simple functions can be implemented based on lambda expressions.

Simple conditional statements can be implemented based on ternary operations, such as:

```num = input("Please write content")

if "Aoi Sora" in num:
data = "The sky is empty without a well"
else:
data = "The stars fall into the sky and the river reflects the pupil"

print(data)
```
```num = input("Please write content")
data = "The sky is empty without a well" if "Aoi Sora" in num else "The stars fall into the sky and the river reflects the pupil"
print(data)

# Result = if condition else does not hold when condition holds
```

lambda expression has nothing to do with ternary operation and belongs to two independent knowledge points.

After mastering the ternary operation, you can deal with slightly more complex situations when writing anonymous functions in the future, for example:

```func = lambda x: "Big" if x > 66 else "Small"

v1 = func(1)
print(v1) # "Small"

v2 = func(100)
print(v2) # "Big"
```

## 2. Generator

The generator is created by the function + yield keyword. In specific cases, using it can help us save memory.

• Generator function. Once yield exists in the function, this function is the production generator function. []

```def func():
print(111)
yield 1
```
• Generator object, a generator object is returned when the generator function is executed.

```def func():
print(111)
yield 1

data = func()
print(data)
# output
<generator object func at 0x00000202D803EB30>

# Execute the generator function func to return the generator object.
# Note: when the generator function is executed, the internal code of the function will not be executed.
```
```def func():
print(111)
yield 1   # After the execution reaches this position, it will not be executed again,

print(222)
yield 2  # Return the value after yield to n1 = next(2)

print(333)
yield 3

print(444)
# When executing a generator function, the function body will not be executed by default, and the return value is a generator object
data = func()
print(data) # <generator object func at 0x00000202D803EB30>

# net, enter the generator function and execute the code in it
v1 = next(data)
print(v1)     # The print result is: 1

v2 = next(data)
print(v2)

v3 = next(data)
print(v3)

v4 = next(data)
print(v4)  # return is encountered at the end or halfway. The program burst: StopIteration error

# Output:
D:\Python\python.exe D:/dw/python/day13/yield.py
Traceback (most recent call last):
File "D:\dw\python\day13\yield.py", line 26, in <module>
v4 = next(data)
StopIteration
<generator object func at 0x000001AE38E8EB30>
111
1
222
2
333
3
444

Process finished with exit code 1
```
```# Execute generator object based on for loop
data = func()

for item in data:
print(item)

# Built in function
next() Returns the next item of the iterator.
next() Function to generate an iterator iter() Function.
```

The feature of the generator is that it records the execution position in the function. The next time it executes next, it will continue to execute downward from the previous position.

### Application scenario

• Suppose you want to generate 300w random 4-digit numbers and print them out.

• Create 300w in memory at one time
• Dynamic creation, create one with one.
```import random

val = random.randint(1000, 9999)
print(val)
```
```import random

data_list = []
for i in range(300000000):
val = random.randint(1000, 9999)
data_list.append(val)

# When reusing, remove the data_list.
# ...
```
```# Compared with the above two methods, it saves more memory.
import random

def gen_random_num(max_count):
counter = 0
while counter < max_count:
yield random.randint(1000, 9999)
counter += 1

data_list = gen_random_num(3000000)
# When reusing, remove the data_list.
```

Therefore, when we need to create a lot of data in memory in the future, we can think of using generator based to realize bit by bit generation (bit by bit production) to save memory overhead.

### extend

```def func():
print(111)
v1 = yield 1 # v1 accepts the value of yield
print(v1)

print(222)
v2 = yield 2
print(v2)

print(333)
v3 = yield 3
print(v3)

print(444)

# The generator object. send() immediately intervenes in the generator function. The first time you wear it must be None
data = func()

n1 = data.send(None)
print(n1)

n2 = data.send(666)
print(n2)

n3 = data.send(777)
print(n3)

n4 = data.send(888)
print(n4)

# yield can only execute generator functions and cannot pass values to the front
# send() executes the generator function and passes values to the variables before yield
```

## 3. Built in function Python internally provides us with many convenient built-in functions. Here, 36 are sorted out for you to explain.

• Group 1 (5)

• abs, absolute

```v = abs(-10)
```
• pow, index

```v1 = pow(2,5) # The 5th power of 2 * * 5
print(v1)
```
• Sum, sum

```v1 = sum([-11, 22, 33, 44, 55]) # Can be iterated - for loop
print(v1)
```
• divmod, find quotient and remainder

```v1, v2 = divmod(9, 2)
print(v1, v2)
```
• round, n digits after the decimal point (rounded)

```v1 = round(4.11786, 2)
print(v1) # 4.12
```
• Group 2: (4)

• Min, min

```v1 = min(11, 2, 3, 4, 5, 56)
print(v1) # 2
```
```v2 = min([11, 22, 33, 44, 55]) # Type of iteration (for loop)
print(v2)
```
```# First put each number into the later function for processing and then compare, but the value is the value before the function processing
v3 = min([-11, 2, 33, 44, 55], key=lambda x: abs(x))
print(v3) # 2
```
• max, max

```v1 = max(11, 2, 3, 4, 5, 56)
print(v1)

v2 = max([11, 22, 33, 44, 55])
print(v2)
```
```# Comparison is to compare the values processed by later functions, but the value is the value before the function is processed
v3 = max([-11, 22, 33, 44, 55], key=lambda x: x * 10)
print(v3) # 55
```
• All, are all True

```v1 = all(   [11,22,44,""]   ) # False
```
• any, whether True exists

```v2 = any([11,22,44,""]) # True
```
• Group 3 (3)

• bin, decimal to binary
• oct, decimal to octal
• Group 4 (2)

• ord, get the unicode code point corresponding to the character (decimal)

```v1 = ord("god")
print(v1, hex(v1))
```
• chr, obtain the corresponding character according to the code point (decimal)

```v1 = chr(27494)
print(v1)
```
• Group 5 (9)

• int

• foat

• str, unicode encoding

• bytes, utf-8, gbk encoding

```v1 = "Raven"  # str type

v2 = v1.encode('utf-8')  # bytes type

v3 = bytes(v1,encoding="utf-8") # bytes type
```
• bool

• list

• dict

• tuple

• set

• Group 6 (13)

• len

• print

• input

• open

• Type to get the data type

```v1 = "123"

if type(v1) == str:
pass
else:
pass
```
• range

```range(10)
```
• enumerate

```v1 = ["Raven", "egon", 'root']

for num, value in enumerate(v1, 1):
print(num, value)
```
• id

• hash

```v1 = hash("Raven")
```
• Help, help information

• pycharm, No
• Terminal, use
• zip

```v1 = [11, 22, 33, 44, 55, 66]
v2 = [55, 66, 77, 88]
v3 = [10, 20, 30, 40, 50]

result = zip(v1, v2, v3)
for item in result:
print(item)

# result

D:\Pyt
on\python.exe D:/dw/python/day13/yield.py
(11, 55, 10)
(22, 66, 20)
(33, 77, 30)
(44, 88, 40)

# Pull down the data of V1, V2 and v3 until the fourth one is gone
```
• callable, whether it is executable and whether it can be followed by parentheses.

```v1 = "Raven"
v2 = lambda x: x
def v3():
pass

print( callable(v1) ) # False
print(callable(v2))
print(callable(v3))
```
• sorted

```v1 = sorted([11,22,33,44,55])
# Reverse order, functions provided by built-in functions
v1 = sorted([11,22,33,44,55], reverse=True)

# Functions provided inside the list
v2 = [1, 2, 3, 4]
v2.sort(reverse=True)
```
```info = {
"peiqi": {
'id': 10,
'age': 119
},
"root": {
'id': 20,
'age': 29
},
"seven": {
'id': 9,
'age': 9
},
'id': 11,
'age': 139
},
}
# key queue
# v1 = sorted(info, reverse=True)
# print(v1)

# Sort according to the id in the value
result = sorted(info.items(), key=lambda x: x['id'], reverse=True)
print(result)
```
```data_list = [
'1-5 Compilers and Interpreters .mp4',
'1-17 Homework today.mp4',
'1-9 Python Interpreter type.mp4',
'1-16 Today's summary.mp4',
'1-2 Creation of classroom notes.mp4',
'1-15 Pycharm Use and crack( win System).mp4',
'1-12 python Installation of interpreter( mac System).mp4',
'1-13 python Installation of interpreter( win System).mp4',
'1-8 Python introduce.mp4', '1-7 Classification of programming languages.mp4',
'1-3 Common computer basic concepts.mp4',
'1-14 Pycharm Use and crack( mac System).mp4',
'1-10 CPython Interpreter version.mp4',
'1-1 Today's summary.mp4',
'1-6 Three essential things about learning programming.mp4',
'1-4 programing language.mp4',
'1-11 Description of environment construction.mp4'
]
result = sorted(data_list, key=lambda x: int(x.split(' ').split("-")[-1]) )
print(result)
```

## 4. Derivation

Derivation is a very convenient function provided in Python, which allows us to initialize some values while creating list, dict, tuple and set through one line of code.

Please create a list and initialize: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9... 299 integer elements in the list.

```data = []
for i in range(300):
data.append(i)

data_list = [ i for i in range(300) ]
```
• list

```num_list = [ i for i in range(10)]

num_list = [ [i,i] for i in range(10)] #[ [0,0],[1,1]... ]

num_list = [ [i,i] for i in range(10) if i > 6 ]

num_list = [ i+100 for i in range(10) if i > 6 ]

num_list = [ "Sun WuKong-{}".format(i) for i in range(10) if i > 6 ] # ['monkey king-7', 'monkey king-8', 'monkey king-9']
```
• aggregate

```num_set = { i for i in range(10)}

num_set = { (i,i,i) for i in range(10)}

num_set = { (i,i,i) for i in range(10) if i>3}
```
• Dictionaries

```num_dict = { i:i for i in range(10)}

num_dict = { i:(i,11) for i in range(10)}

num_dict = { i:(i,11) for i in range(10) if i>7}

num_dict = { i:"root-{}".format(i) for i in range(10)}
```

The above types will generate data immediately.

• Tuples, different from other types.

```# Instead of immediately executing an internal loop to generate data, you get a generator.
data = (i for i in range(10))
print(data)
for item in data:
print(item)

# In addition to the for loop, the generator can also use yield,send() to process
```

### Exercises

1. Remove the. mp4 suffix from each element in the list.

```data_list = [
'1-5 Compilers and Interpreters .mp4',
'1-17 Homework today.mp4',
'1-9 Python Interpreter type.mp4',
'1-16 Today's summary.mp4',
'1-2 Creation of classroom notes.mp4',
'1-15 Pycharm Use and crack( win System).mp4',
'1-12 python Installation of interpreter( mac System).mp4',
'1-13 python Installation of interpreter( win System).mp4',
'1-8 Python introduce.mp4', '1-7 Classification of programming languages.mp4',
'1-3 Common computer basic concepts.mp4',
'1-14 Pycharm Use and crack( mac System).mp4',
'1-10 CPython Interpreter version.mp4',
'1-1 Today's summary.mp4',
'1-6 Three essential things about learning programming.mp4',
'1-4 programing language.mp4',
'1-11 Description of environment construction.mp4'
]

result = []
for item in data_list:
result.append(item.rsplit('.',1))

result = [ item.rsplit('.',1) for item in data_list]
```
2. Format the elements in the dictionary according to the key value and use them finally; Connect.

```info = {
"name":"Raven",
"email":"xxx@live.com",
"gender":"male",
}

data_list []
for k,v in info.items():
temp = "{}-{}".format(k,v)
temp.append(data_list)
resutl = ";".join(data)

result = ";".join( [ "{}-{}".format(k,v) for k,v in info.items()] )
```
3. Sort the dictionaries from small to large according to the key, and then splice them according to the following format. (internal processing requirements of wechat payment API)

```info = {
'sign_type': "MD5",
'out_refund_no': "12323",
'appid': 'wx55cca0b94f723dc7',
'mch_id': '1526049051',
'nonce_str': "sdfdffd",
'total_fee': 9901,
'refund_fee': 10000
}

data = "&".join(["{}={}".format(key, value) for key, value in sorted(info.items(), key=lambda x: x)])
print(data)
```
4. Look at the code writing results

```# The function is not called, and the internal code of the function is not executed
def func():
print(123)

data_list = [func for i in range(10)]

print(data_list)

# The function is not called, and the internal code of the function is not executed
data_list = [lambda: 100 for i in range(20)]
print(data_list)
```
5. Look at the code writing results

```def func(num):
return num + 100

data_list = [func(i) for i in range(10)]

print(data_list)
```
6. Look at the code writing results (execution errors, through which you can better understand the execution process)

```def func(x):
return x + i

data_list = [func for i in range(10)] # The function is not called for execution, and i=9

val = data_list(100)
print(val)
# The reason for saving is i not defined
```
7. Look at the code writing results (Sina Weibo interview questions)

```data_list = [lambda x: x + i for i in range(10)]  # [function, function, function] i=9

v1 = data_list(100)
v2 = data_list(100)
print(v1, v2)  # 109 109
```

### Deductive nesting

```be based on Lambda The defined function format is:`lambda parameter:Function body`
Ternary expression:
result =  When conditions are met    if   condition   else   Not established
Derivation:
data = [ i for i in range(10)]
```
1. Derivation supports nesting

```data = [ i for i in range(10)]
```
```data = [ (i,j) for j in range(5) for i in range(10)]

data = []
for i in range(10):
for j in range(5):
data.append( (i,j) )

data = [ [i, j] for j in range(5) for i in range(10)]
```
```# A deck of playing cards

poker_list = [ (color,num) for num in range(1,14) for color in ["heart", "spade", "Square slice", "Plum blossom"]]

poker_list = [ [color, num] for num in range(1, 14) for color in ["heart", "spade", "Square slice", "Plum blossom"]]

print(poker_list)

# Recycle the inner layer and recycle the outer layer first
```
2. Brain burning interview questions

```def num():
return [lambda x: i * x for i in range(4)]

# 1. Execute num() and get the return value [function, function, function] i=3
# 2. Return value of for loop
# 3. Each element of the return value (2)
result = [m(2) for m in num()]  # [6,6,6,6]
print(result)

```
```def num():
return (lambda x: i * x for i in range(4))

# 1. num() and get the return value generator object
# 2. Return value of for loop
# 3. Each element of the return value (2)
result = [m(2) for m in num()]  # [0,2,4,6 ]
print(result)
```

## summary

1. Anonymous function, create a function per line based on lambda expression. It is generally used to write simple functions.
2. Ternary operation, with a line of code to deal with simple condition judgment and assignment.
3. Generator, if the yield keyword in the function
• generator function
• Generator object
• Execute the code in the generator function
• next
• for (common)
• send
4. Built in functions (36)
5. Derivation
• General operation