Fourth day built-in function 2 random code adorner iterator, generator recursive bubbling algorithm JSON

Source: Internet
Author: User
Tags pow

About Return of a function

Li = [11,22,33,44]

def f1 (ARG):

Arg.append (55)

Li = F1 (LI)

Print (LI)

Because li = F1 (LI) is actually assigned a return of F1, in this case the function F1 does not define return, so the default return is None

So the value of Li should be none

If it is

Li = [11,22,33,44]

def f1 (ARG):

Arg.append (55)

F1 (LI)

Print (LI)

Because the arguments passed by the function are actually references to the arguments, the changes to the arguments in the function affect the original parameters, so the return is 11,22,33,44,55

Converts a string to a specific encoded byte type

s = "Liu Bo"

Bytes (s,encoding= "Utf-8")

Built-in function supplement

Callable () Determines whether an object can be executed, the function can be executed

Chr () Converts the sequence in the encoded table to the corresponding character, 2.7 Nate refers to the ASCII code

Ord () Converts the characters in the encoding table to the corresponding sequence number, with a special ASCII code in 2.7

Random Verification Code

Import Random #这个函数用来随机生成数字

TEM = Random.randrange (65,91) #指定随机生成数字的范围

c = chr (TEM) #然后我们可以使用chr (i) converts i to the corresponding character

In the ASCII Code table 65-91 represents the case of 26 letters

If you are generating multiple random codes at once, you can

Li = []

For I in range (6):

TEM = Random.randrange (65,91)

c = chr (TEM)

Li.append (c)

"". Join (LI) #将生成的列表形成字符串

If a number is required

Li = []

For I in range (6):

if i = = 2 or i = = 4:

TEM = Random.randrange (0,10)

Li.append (str (TEM)) #因为在向列表中添加元素时, you need to use a string type, so ASCII 0-10 is a number so you need to convert it to a string type

Else

TEM = Random.randrange (65,91)

c = chr (TEM)

Li.append (c)

result = "". Join (LI) #将生成的列表形成字符串

Print (Result)

The position of the number in the above example is fixed, and if you want the random number to be random, the position of the number is stochastic.

Li = []

For I in range (6):

R = Random.randrange (0,6)

if r = = 3 or r = = 2:

TEM = Random.randrange (0,10)

Li.append (str (TEM)) #因为在向列表中添加元素时, you need to use a string type, so ASCII 0-10 is a number so you need to convert it to a string type

Else

TEM = Random.randrange (65,91)

c = chr (TEM)

Li.append (c)

result = "". Join (LI) #将生成的列表形成字符串

Print (Result)

Complie ()

Eval ()

EXEC ()

Any python file, the computer will be read into a string, compile, execute three stages.

Complie () is the action used to compile the string.

s = "Print (123)" #s的值是字符串

R = Complie (S, "<string>", "exec") #r的值就是s编译后的结果, where the position of s in Complie can also be a file name, if the file name does not require the following string argument, The exec parameter has 3 values: Single eval exec. If you select single mode, the string you get will be compiled into one-line program, and if it is eval, it will be compiled into an expression, and if Exec is compiled according to the original Python code

EXEC () is used to execute compiled code, and Complie, first compiled with Complie, and then executed with exec. EXEC can execute all the Python commands, exec just executes no return value, so running an expression with exec is not getting results, such as exec ("7+8+9"), but the result is not available. Exec can accept the code or string when executing the code.

Eval () is used to compile a string into an expression, such as S = "8*8" R = eval (s), when print (R) is returned as 64,eval can only execute an expression, eval has a return value, if using eval ("7+8+9"), is able to return results, this is stronger than exec , versus exec.

Dir () quickly gets an object in a class of function print (dir (dict)), viewing the functions provided in the dictionary function

Help () Gets a detailed explanation of the functionality provided by an object, and Dir only describes the function name, which is explained.

Divmod () is used to get the integer and remainder of a number divided by another number in the form of a tuple, R = Divmod (97,10), and print (R) return (9,7), since the default return is always 2 numbers, so you can use N1,N2 = Divmod (97,10) will automatically give N1 = 9, N2 = 7

Serialization of Enumerate ()

The instance () object is an instance of the class, S = "Alex" Then Alex is an object created from the class str, so Alex is an instance of the class str, and the class is a template, and the object is an instance of the template. s = "Alex" R = Isinstance (S,STR) determines if S is an instance of the Str class, and print (R) returns True

Filter () filter (function, iterative object) when the filter is executed, the first loop can iterate over the object, the inside of each loop executes the function filled in the first parameter, and get the result of the function, if the result is true, the element of the loop will be added to a list

Li = [11,22,33,44]

Def f1 (a)

If a > 22

Return True

RET = Filter (F1,li)

Print (list (ret))

[33,44] is returned, filter is filtered based on the provided function for the iteration object.

The filter above is implemented using lambda expressions.

Li = [11,22,33,44]

RET = filter (lambda a:a>22,li)

Print (list (ret))

Map () map (function, iterative object), when the map is executed, first loop the iterated function, and then each time the result of the loop is taken into the previously passed function, and run the returned result defined in the function, append it to a new list

Li = [11,22,33,44]

Def f1 (a):

Return a + 100

ret = map (F1,li)

Print (list (ret))

The result is [111,122.133.144]

You can also use lambda expressions

Li = [11,22,33,44]

ret = map (lambda a:a+100, Li]

Print (list (ret))

The filter () function returns True to add the result to the list

Map () Adds the result of the function to the list

Globals () represents all global variables, output type is dictionary, print (Globals ()) prints all global variables in the current code in dictionary type output

Locals () represents all local variables, output type is dictionary, print (local ()) prints all local variables in the current code in dictionary type output

Hash () generates the hash value of the corresponding content s=123 print (hash (s)), in the Python storage Dictionary key is now the key to hash algorithm after the storage, because the hash algorithm calculates the value is a fixed length, So no matter how long the key is actually stored, it is the same length value. That's how all the languages are done. This facilitates storage and also facilitates lookups.

Len () looks at the length of the variable, in Python3, in bytes, in python2.7, so if you want to calculate the length of the byte in Python3, you should first turn the variable into bytes.

s = "Li Jie"

The print (Len (s)) result is 2 by character,

s = "Li Jie"

b = Bytes (s,encoding= "Utf-8")

Print (b) result is 6 by byte

Max () finds the maximum value in a sequence

Min () find the smallest value in a sequence

SUM () sequence sum

Memoryview () A class related to memory address

Object () is the parent class of all classes

Pow () squared, generally written as 2**10 represents 2 of the 10, but also read as POW (2,10)

Range () specifies a range

Reversed () flip

Round () Rounding a decimal

Slice () slices

Sort () sorts (list) equals list. Sort

Zip () passes in multiple lists, and the zip will spell the first element of all the lists as a tuple, the second element to a tuple, and so on. When the element length is different, it will only be stitched to the location where the list element is least.

l1=["Liubo", 23,19]

L2=[33,55]

l3=["AA", "CC", 22,55]

L4=zip (L1,L2,L3)

Print (List (L4))

The output result is

[(' Liubo ', ' x ', ' AA '), (at +, ' cc ')] # only to Stitch to the second element, because L2 has only 2 elements

The Dark box is going to be, tick is used more commonly

JSON can convert a string to a corresponding type from its form, or it can convert data of the corresponding type to a string in the original format

s = "[11,22,33,44]" # This is a string instead of a list

n = json.loads (s) # In this way, the string of S is converted into a list, and the dictionary can also write the corresponding format in the file to Python as a specific data type

s = [11,22,33] # This is a list

n = json.dumps (s) # This can be used to convert it to a string, but the format is still the format of the list as in the example above, such as can be used to write to the file, write the file must be a string

Conversions are usually not possible because conversions are cross-lingual, but tuples () are unique to Python

When using a transform, if you want to convert a string to a dictionary or list by loads, the string element inside the string must be enclosed in double quotation marks

Decorative Device

function development has open closed rules, that is, the function itself is closed can not be arbitrarily rewritten, but in the external is open to call this function. However, if you want to batch modify multiple functions, you need to use the adorner. That is, without changing the original function, add function

Define a s1.py, the code is as follows

def outer (func):

def inner ():

Print ("Log")

return func ()

return inner

@outer

Def f1 ():

Print ("F1")

@outer

def f2 ():

Print ("F2")

@outer

Def f3 ():

Print ("F3")

This will perform the function in the outer function first when someone else calls the F1 function. The outer function is an adorner that increases the function of the F1 function through the adorner without changing the function of the F1 function.

Call Method:

Create a new py file

Import S1 # Imports the previously created S1 into your code

S1.F1 () # Call the F1 function in the S1 code

The result is

The output of the log # outer adorner

F1 # Output of the F1 function

Adorner prerequisite knowledge points:

1.

Def f1 ():

Print (123)

Def f1 ():

Print (456)

F1 ()

The execution F1 prints 456 because Python is a line of code to load, so the second F1 will point F1 to the print (456) method

2.

Def f1 ():

Print (123)

def f2 (XXX):

XXX ()

F2 (F1)

The argument to the function can be another function, so the output 123

@ + function name is adorner

@outer Features

1. Automatically executes the outer function and passes it the function name F1 as a parameter (the function name refers to the entire function, the name of the functions () is the execution function)

2, the return value of the outer function is re-assigned to F1

So:

def outer (func):

def inner ():

Print ("before")

return inner

@outer

Def f1 ():
Print ("F1")

The procedure for executing the above function is

1, first the system will automatically execute the outer function, and F1 as a parameter to the outer function

2. The outer function internally defines a new function inner, which prints before

3. The outer function returns the inner function

4. Outer function re-assigns return value inner function to F1

5. At this point the function contents of F1 () are replaced in order to inner content

6, so the F1 () function is executed when printing before instead of F1

So the fact that the adorner is the function F1 the next line of the @ is replaced by the function returned by outer. Then we do the operation before or after a function by the adorner to add function before or after the action is actually the function of outer inner layer function

def outer (func):

def inner ():

Print ("before")

Func ()

Print ("after")

return inner

@outer

Def f1 ():

Print (123)

The func in the inner layer function of the outer function above is actually the original function body of the F1, because @outer passes the original function body of F1 to the Func parameter. So the operation of the inner function is to execute the before before executing the F1 and then execute the F1 last after

Defines a function that is not called and does not execute inside the function

Function name refers to the entire function, the function name () is the execution function

def outer (func):

def inner ():

Print ("before")

Func ()

Print ("after")

return inner

@outer

Def f1 ():

Print (123)

So in this example, the return value of the outer function must be inner instead of inner (), because the purpose of doing this is to return the function body of inner to F1, otherwise if return inner (), the return value of the inner function definition returned, And this function we did not specify returns, by default returns to None. In this way, the function F1 is also replaced with none. Even if inner defines the return value, it's not what we want. We want the inner function body, not the return value.

If the original function defines a return value

Then the function inner in the adorner will have no return value, because only func () is executed in inner and the return value is not obtained. So we need to get this return value to the

So the complete decorator should be written into the next

def outer (func):

def inner ():

Print ("before")

R = func () # executes the original function and gets the original function return value

Print ("after")

Return R # Returns the return value of the original function

return inner

If the original function defines a parameter

The function of the adorner should use the universal parameters to solve the problem of the original function with parameters.

def outer (func):

def inner (*args,**kwargs):

Print ("before")

R = Func (*args,**kwargs) # Here Python will directly pass the parameters in inner into the func.

Print ("after")

Return R # Returns the return value of the original function

return inner

Recursive

A function calls itself internally, which is recursion.

Requirements for recursive characteristics:

1. Must have a definite end condition

2, each time into a deeper level of recursion, the problem size should be reduced compared to the last recursion

3, recursive efficiency is not high, too many recursive hierarchy will lead to stack overflow (in the computer, the function call is implemented through the data structure of the stack, whenever entering a function call, the stack will add a stack of frames, whenever the function returns, the stack will reduce the stack frame. Due to the size of the stack is not infinite, so too many recursive calls, will cause stack overflow)

Fourth day built-in function 2 random code adorner iterator, generator recursive bubbling algorithm JSON

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.