Python common basic interview questions

Posted by mark s on Thu, 17 Feb 2022 17:57:59 +0100

Interview questions

Talk about your understanding of object orientation

Facing objects is a programming idea and a way to look at things from the perspective of classes. Encapsulate things with common properties and methods under the same class.
    Definition: put data processing and business implementation logic inside an object, and the outside world can only access the object through an open interface
    Benefits: hide object implementation details, easy to maintain and improve security
    Definition: a parent-child relationship is generated between classes. Multiple inheritance is found according to the writing order of classes
    Benefits: subclasses can obtain the properties and methods of the parent class;
    Implementation method: overlay inheritance, extended inheritance super()
Polymorphism: (python dynamic weakly typed language, Java static strongly typed language)
    Definition: polymorphism is the same interface that uses different instances to perform different operations
    Implementation method: Rewrite, interface, abstract class and abstract method
    The advantage of polymorphism: it can make the program have good expansion, and can deal with all kinds of objects in general

Explain inheritance in Python

When a class inherits from another class, it is called a subclass / derived class, which inherits from the parent class / base class / superclass. It inherits / gets all class members (properties and methods).
Inheritance allows us to reuse code and make it easier to create and maintain applications. Python supports the following types of inheritance:
Single class inheritance: a class inherits from a single base class
 Multiple inheritance: a class inherits from multiple base classes
 Multi level inheritance: a class inherits from a single base class, which inherits from another base class
 Hierarchical inheritance: multiple classes inherit from a single base class
 Mixed inheritance: a mixture of two or more types of inheritance

What is the Python garbage collection mechanism

python adopts a policy counting mechanism, which is mainly a reference counting mechanism, supplemented by two mechanisms: mark clear and generational collection (inter generational recycling and generational recycling)
When an object is referenced, the reference count is added by 1. When the object is del, the reference count is subtracted by 1. When it is 0, the object is cleared. Generally, users will not operate Python's garbage collection mechanism, but it has an API interface.

What is python introspection

The runtime can know the type of object and check something to determine what it is, what it knows and what it can do. Introspection provides programmers with great flexibility and control.
Common introspection mechanisms (function usage) in Python include: dir(), type(), hasattr(), isinstance()
Dir (): returns a sorted list of attribute names of any object passed to it. If no object is specified, dir() returns the name in the current scope
 type(): determines whether the object is a string, an integer, or an object of other types
 isinstance(): determines whether the object is an instance of a specific type or custom class

How to get command line parameters in python?

import sys
 sys.argv # receives command line parameters entered by the user

How are classes and objects stored in memory?

A class only needs to save a copy in memory, while an instance of a class is an object. Once instantiated, it needs to be saved in memory, and there is a class object pointer to the class instantiated by the object
When object1 executes the def method:
1 -- the method of the class will be found according to the class object pointer of the current object
 2 -- if the method requires parameters, the first parameter of the class object, self, will be passed in to execute the method

Enumerate special methods with double underscores in object-oriented

__ new__:  Generate instance
 __ init__:  This method is automatically called to allocate memory when a new object / instance of a class is created. All classes have__ init__ method
 __ del__:  Destruct method, which automatically triggers execution when the object is released in memory. For example, when del obj or the application is running, execute the contents in this method
 __ class__ :  What is the class that represents the object of the current operation
 __ str__:  Change the string display print function of the object
 __ format__:  Custom format string
 __ get__ (): triggered when a property is called
 __ set__ (): triggered when an attribute is assigned a value
 __ delete__ (): triggered when del is used to delete attributes

What are the common modules?

Built in modules (Libraries):
Third party modules (Libraries):
requests,pymysql ,bs4,petermaterized,HTMLTestRunner,openpyxl,Django,Flask,selenium,appium-python-client 

The role of os and sys modules?

os module is responsible for the interaction between the program and the operating system, and provides the interface to access the bottom of the operating system;
sys module is responsible for the interaction between the program and python interpreter, and provides a series of functions and variables to manipulate the runtime environment of python.

If the module is imported, what is the value of name? If it is executed, what is the value of name?

When imported__ name__ The value of is the file name of this module
 When executed__ name__ == "__main__"

Function scope and order

50: Internal scope of local function 
E: Between enclosing function and embedded function (closure)
G:global scope 
B: Build in built-in scope
Execution sequence from inside to outside

How to judge whether it is a function or a method?

    No instance objects need to be passed in
    The instance method is called by the instance object, and there is no need to pass in the instance object;
    An instance object needs to be passed in
    The function is called by a class, and the instance object needs to be passed in

Instance method, static method, class method

1. The instance method can only be called by the instance object. The first parameter must be passed to the instance object by default. Generally, self is used
 2. Class method (method by @ classmethod decorator), class or instance object of class
 3. Static methods (@ methods decorated by staticmethod), classes and instance objects can be called

What are methods bound to objects, methods bound to classes, and unbound methods

Method bound to Object > > instance method
 Method bound to class > > class method
 Unbound method > > static method

*arg and * * kwarg action

*args represents location parameters. It will receive any number of parameters and pass these parameters to the function as the ancestor
 **The keyword parameter represented by kwargs returns a dictionary. The location parameter must be placed in front of the keyword parameter

How to set a global variable in a function

Global statements are used to declare global variables

Talk about python's small data pool

Number in python. Within certain rules, if multiple numeric or string variables with the same value are defined at the same time, they will share a memory address. It can be verified with is.
Number: Range - 5 ~ 256
 The purpose of small data pool is to save memory space

List common values whose Boolean value is False?


There is no difference between null and None strings

1. The data type of none is NoneType, and the data type corresponding to an empty string is string
 2. Used to judge whether Boolean is false;
3. As the parameter of dir() function, the returned attribute and method lists are different

Efficiency of in operation for list, set, tuple and Dict

The efficiency of set/dict is higher than that of list/tuple

data typeAverage time complexity of lookup using the in operator

What is the difference between json and dictionary?

json() is essentially a string str type, which is a string in the format of key:value pairs
 Dictionary: it is a data type in python language (int, STR, float, bool, dict, tuple, list)

Which is faster to find a dictionary or a list?

The dictionary is faster because it uses a hash table, and the lookup of the list is to traverse the whole list

List, tuple, dictionary, set

Ordered: list, tuple, dictionary
 Unordered: Collections
 Dictionary: key determines the storage address of value through hash function. Key value can be integer, string and tuple
Variable data types: list, dictionary
 Immutable data types: integer, string, tuple
Why is it called variable data type?
    The address changes after the immutable data type is changed, and the address does not change after the variable data type is changed

The difference between tuples and lists

Lists are mutable and tuples are immutable
 Different definitions

Tuples can be used as dictionary key s?

Tuples can be used as key s of dictionaries
set/dict uses hash value for indexing, and the stored elements are required to be hashable. Therefore, list and dict types cannot be used as dictionary keys, while tuples, integers and strings can be used as dictionary keys

Common methods of string, list, tuple and dictionary

Common methods of string

The string is an immutable type. After the method is executed, a new string is generated without changing the original string
character string. Find (find character, start position, end position) # returns the first subscript value (integer), otherwise - 1 is returned
 character string. Replace (original string, new substring, replacement times) # return type is string
 character string. Join (string / string type list / string type tuple / string type Dictionary) # return type is string
 character string. The default value is' num ', and the default value is' # all' # separator

List common methods

List: variable data type. Note that some methods have no return value and directly operate the original list
List [index] # returns the corresponding value of the index
 List [index] = new data # modify element value, use nonexistent index, code execution will report error!
List Count (target data) # counts the number of times the tested value appears. If the target data does not exist, 0 is returned
List Insert (index, new data) # has no return value; When an index does not exist, data is inserted at the end of the list by default
 List Append # has no return value; If the new data is a container type (for example, list) data, the whole data will be added to the end as an element
 List Extend (string or iteratable object) # has no return value; Strings and iteratable objects are split and appended to the end of the list
List Pop (index) # returns the deleted data value. If the index value is not passed in, the last data in the list will be deleted by default. If the index does not exist, an exception will be thrown
 List Remove (target data) # has no return value. If there are multiple target data in the list, only the first matching data will be deleted; If the target data does not exist, an exception will be thrown
 List clear() # clear list data
List reverse() # no return value; Reverse the list!
List sort() # ascending the data in the list
 List sort(reverse=True) # sorts the data in the list in descending order

Common methods of tuples

Tuples: immutable data types
Tuple variable = data 1, data 2, data 3 # grouping operation
 Variable 1, variable 2, variable 3 = tuple variable # unpacking operation
 Tuples count('objects to be counted ') # returns the number of objects to be counted

Dictionary common methods

Dictionary: variable data type. Some methods are to operate on the original dictionary
DICTIONARY ['key'] = value # if the key does not exist, increase the key value pair; If the key exists, modify the value corresponding to the key
 [print(key) for key in info.keys()] # print all key values
 [print(value) for value in info.values()] # print all value values
 [print (key, value) for key, value in info. Items()] # print all key and value values
Dictionaries. Pop (key) # returns the value corresponding to the key. If the parameter is empty or does not exist, an exception will be thrown
 DICTIONARY [key] # returns the value corresponding to the key. If the parameter is empty or does not exist, an exception will be thrown
 Dictionaries. Get (key) # returns the value corresponding to the key. If the parameter is empty, throw an exception. If the key does not exist, return None
Dictionaries. clear() # return {}

String splicing can be completed with + and join. What's the difference between the two?

The string belongs to the immutable data type. Every time + is executed, a new memory address will be applied. Therefore, when + is used to connect, there will be multiple memory applications and copies;
When using join to connect strings, you will first calculate how much memory is needed to store the results, and then apply for the required memory at one time. It is recommended to use join when splicing strings

File operation

patternDo operationIf the file does not existOverwrite
rCan only readreport errors-
r+Readable and writablereport errorsyes
wCan only writeestablishyes
w+Readable and writableestablishyes
aCan only writeestablishNo, append write
a+Readable and writableestablishNo, write
1. Open the file in r +, w, w +, a and a + mode, and you can write it;
2. When the file is opened in w or w + mode, the program will immediately empty the contents of the file;
3. When opening a file in r,r+,w,w + mode, the file pointer is at the beginning of the file;
4. When opening a file in a,a + mode, the file pointer is at the end of the file;


The use of the with statement can simplify the code and effectively avoid resource leakage
When opening a file for reading and writing, some exceptions may occur. If we follow the conventional writing method, we need to try, except and finally to judge the exceptions. In the end, no matter what happens to the file, we need to execute finally f.close() to close the file. The with method helps us realize f.close() in finally

Open file

Mode 1:
    File variable = open('File name','Access mode')
    File operation
    File variable.close()
Mode 2:
    with open('File name','Access mode') as f:
1.The file name and access mode are all string types
2.If you work with text files, encoding='utf-8'Specify for utf-8 Coding to prevent Chinese garbled code on different platforms
    - The access mode is not binary('w','r'),It is recommended to specify the encoding when opening a file
    - If the access mode is binary('wb','rb'),Must not be specified encoding
3.Access mode
'w': Open the file in write only mode, the file does not exist, create the file, and empty the file content
'r': The default value is to open the file in read-only mode. If the file does not exist, an error will be reported
'a' open for writing,appending to the end of the file if it exists
'x' create a new file and open it for writing
'b' binary mode

read file

with open('File name','r',encoding='utf-8') as f:
	data = length) #If the length of read is not specified, all are read by default
with open('File name','r',encoding='utf-8') as f:
    while True
        data = f.readline()
        if data: # Judge the content
        elif not data:  # Judge no content
            break # End cycle 

Write operation

with open('File name','w',encoding='utf-8')) as f: 

seek(offset[, whence])

Move the file reading pointer to the specified position, index Start from 0 offset -- Start offset whence: 0 Represents from the beginning of the file, 1 represents from the current position, and 2 represents from the end of the file

test.txt Content:
with open('test.txt','a+') as f:
    print( #2345abc

truncate([ size ])

truncate([ size ])
If the length is specified, truncate the specified length from the beginning of the file, and delete the rest;
If the length is not specified, delete all contents after reading the pointer position;
test.txt Content:
with open('test.txt','a+') as f:
    print( #01
with open('test.txt','a+') as f:
    print( #empty
with open('test.txt','a+') as f:
    print( #01

In the file operation, f = open(filename, mode, code), execute write f.write('hello world '), is hello world written into the file or just stored in memory? How to make the written content actively stored in the file

f.write Is to write the contents to the memory of the computer
 Store to file:
    f.close()# When the file is closed, the contents will be automatically stored from memory into the file
    f.flush()# Proactively store content from memory to files
flush() The method is used to refresh the buffer, that is, the data in the buffer is written to the file immediately, and the buffer is emptied at the same time. There is no need to wait passively for the output buffer to be written.
Generally, the buffer will be refreshed automatically after the file is closed, but sometimes you need to refresh it before closing, so you can use it flush() method.

How to operate the database?

#Import pymysql
    import pymysql
#Establish connection
    conn = pymysql.connect(host='',port=7061,
#Get cursor
    cursor = conn.cursor()
#Execute query statement
    cursor.execute('select version();') #Returns the number of affected rows
#View query results
    resp = cursor.fetchall()
    resp = cursor.fetchone()
    resp = cursor.fetchmany(6)
#Close cursors and connection objects
#Execute dml statement
    n = cursor.execute('delete from table where id = '1';')
except Exception as e:
    # If there is an exception, roll back the transaction
    # No exception, commit transaction
    # Close cursors and connection objects

What is the function of the logging module? And application scenarios?

The functions and classes defined in the module implement a flexible event log system for the development of applications and libraries
 You can understand the operation of the program and whether it is normal
 In case of program failure, quickly locate the wrong place and fault analysis

break, continue, pass, exit()

break: jump out of the loop and no longer execute
break statements are used in while and for loops
If nested loops are used, the break statement will stop executing the deepest loop and continue to execute the external loop;
continue: jump out of this cycle and execute the next one
The continue statement is used in while and for loops
pass: only to maintain the integrity of the program structure, do nothing, and only play the role of occupying space
    The exit program throws a SystemExit exception, which can be caught and cleaned up
    n the default value is 0, which means normal exit, and others are abnormal exit
    Used to exit in the main thread
    Exit directly without throwing exceptions and performing relevant cleaning work
    It is often used in the exit of child processes
    Throw SystemExit exception
    exit(1) indicates that an error has occurred
    exit(0) indicates that the program exits normally

Exception handling, universal exception, throw exception

 Exception 1:
except Exception:
 pass # universal exception
 There is no exception, except does not meet the requirement to execute else
 Whether there are exceptions or not, it should be executed in the end
Actively throw exception
raise [Exception [,args [,traceback]]]

isinstance function and application scenario?

Isinstance (object, class) determines whether the object is an instance of this class or a subclass of this class


id check the memory address. Is is to compare whether the memory address is the same, = is the assignment, = = compares the value of the variable
id() returns the memory address of the object
 Is compares whether the two instance objects are identical, whether they are the same object, and whether the memory addresses occupied are the same. If the memory addresses are the same, it is True
 ==The comparison is whether the contents of the two objects are equal, that is, the memory address can be different, and the contents can be the same. By default, the object will be called__ eq__ () method
 [if the memory addresses are the same, the values must be the same, but if the values are the same, the memory addresses are not necessarily the same]

serialization and deserialization

Correspondence table between json data type and python data type

Jason typePython type
520.13int or float

json and pickle modules

json and pickle Modules, both of which are used for serialization and deserialization
• json Module for string and python Conversion between data types
• pickle Module for python Unique types and python Conversion between data types, Python specific
Both modules provide dumps,dump,loads,load 4 Functions
 Serialization: convert to str,dumps/dump
 Deserialization: convert to dict,loads/load
import json
struct_data = {'name': 'json', 'age': 23, 'sex': 'male'}
data = json.dumps(struct_data)
data = json.loads(data)
with open('Json serialized objects .json', 'w') as fw:
    json.dump(struct_data, fw)
with open('Json serialized objects .json') as fr:
    data = json.load(fr)
import pickle
struct_data = {'name': 'json', 'age': 23, 'sex': 'male'
data = pickle.dumps(struct_data)
res = pickle.loads(data)
# Serialization (Note: pickle module needs to use binary storage, that is, 'wb' mode storage)
with open('Pickle serialized objects .pkl', 'wb') as fw:
    pickle.dump(struct_data, fw)
# Deserialization
with open('Pickle serialized objects .pkl', 'rb') as fr:
    pickle = pickle.load(fr)

Differences between dumps/dump/load/loads

dumps converts dict into str and serializes it
 loads converts str to dict and deserializes it
dump and load operate on files

When serializing json, Chinese will be converted to unicode by default. What if you want to keep Chinese?

During serialization, Chinese characters are always converted into unicode code, and the parameter ensure is added to the dumps function_ ASCII = false.
dict_temp = {'a': 1, 'b': 2}
str_result = json.dumps(dict_temp,ensure_ascii=False)

The difference between match/search/findall of re

Is it a regular greedy match?

(. *) greedy pattern. There is no restraint in matching a string. You can match as many as you can until there is no match
(.*?) Non greedy mode will match as few as possible

lambda expression format and application scenario?

Anonymous function: a one sentence function designed to solve the requirements with simple functions
 Application scenario: Functions are passed as arguments,It is often used in combination with some built-in functions, such as map(),filter(),sorted(),reduce()etc.
Function name = lambda parameter:Return value
#There can be multiple parameters separated by commas
#Anonymous functions can only write one line no matter how complex the logic is, and the content after the logic execution is the return value
#Like normal functions, the return value can be any data type
lambda expression
temp = lambda x,y:x+y
print(temp(4,10))   # 14
def foo(x,y):
    return x+y
print(foo(4,10))    # 14

Closure of python

1.Nested functions exist
2.The return value of an external function is an embedded function
3.Embedded functions can access variables of external functions, but cannot modify variables
def func(num):
    print('get into func')
    def func_in():
        print('get into func_in')
    print('end func')
    return func_in
temp = func(2)
get into func
 end func
 get into func_in

Writing method and application scenario of decorator

Meaning: the essence of decorator is function. Function decorator reasonably expands the function of function through decorator function without modifying the original function. It is an application of closure function.
The function modified by "@ function" is no longer the original function, but is replaced with a new one (depending on the return value of the decorator). That is, if the return value of the decorator function is an ordinary variable, the modified function name becomes the variable name; Similarly, if the decorator returns the name of a function, the decorated function name still represents a function.
Do not modify the code of the modified function
 The calling method of the modified function is not modified
Application scenario:
-Flash routing system
-flask before_request
 -django built in authentication
 -django cache
 -Nonparametric decorators are common in user login authentication
 -The reference decorator has been seen in the routing system of flash

What is a recursive function? What should we pay attention to in the use of recursive functions?

Recursive functions call themselves.
be careful:
1. Recursive functions need to have an explicit end condition. Otherwise, it will recurse infinitely, exceeding the maximum recursion depth of python. (the sys module can modify the recursion depth, which is 1000 by default)
2. Each time you enter one layer of recursion, the scale of the problem should be smaller than that of the previous layer.
3. Recursive efficiency is not high. Only for special places.

What is the maximum number of layers of python recursion?

Generally, the default maximum recursion depth of the computer is about 1000, python The maximum recursion depth is generally about 4000, which is similar to the calculation
 It is related to the performance of the machine. This number is not a fixed number. It can be tested in the following ways
import sys

Assignment, light copy and deep copy

Assignment: no new object is created, which is an alias of the original object. The object id and the object element id are the same;
Shallow copy: a new piece of memory will be allocated to create a new copy object, but the elements in the copy object are still the elements in the original object (copied object), that is, the id of the copy object is different from that of the original object, but the elements in the two have the same id;
Deep copy: a new piece of memory will be allocated to create a new copy object. The elements in the copy object are copied one by one through recursion (except for variable elements, which will create a new object, and then point to the elements of the new object after assigning values to the corresponding elements of the original object), That is, the object and the element in the object are different IDS, and they are completely independent
1. The elements in the copied object have only values and no references. There is no difference between shallow copy and deep copy
 2. The copied object contains references. Modifying the referenced elements will have an impact on shallow copy (without copying references) and no impact on deep copy (copying references)
Shallow copy copies the reference of an object to another object. The modification of the object affects each other. Use copy Copy (copied object)
Deep copy uses copy Deepcopy (copied object) copies one object to another, and the two objects do not affect each other

Briefly describe the keywords yield and yield from (the difference between yield and return)

The usage of yield in python is very similar to that of return. Both yield and return provide a return value, but the biggest difference between yield and return is that once return is returned, the execution of the code segment ends, but yield will hand over the right to use the CUP after returning the value. The code segment does not end directly, but is interrupted here. When the send() or next() method is called, Yield can continue from where it was previously interrupted
In a function, if you use the yield keyword, the current function will become a generator. You can use next() to easily traverse the generator object
yield from applies to the nesting of multiple generators

Briefly describe generators, iterators, iteratable objects, and application scenarios?

Contain__ iter__ And__ next__ Method (the iteratable object containing the _next _methodis the iterator)
Including the keyword yield. The generator is also an iterator. Call next to turn the function into an iterator
Iteratable objects: list, dictionary, tuple
 Internal implementation of a class__ iter__ Method and returns an iterator

Iterators and generators

An iterator is an object that remembers where to traverse.
The iterator object is accessed from the first element of the collection until all the elements are accessed. Iterators can only move forward, not backward.
Iterators have two basic methods: iter() and next().
String, list, or tuple objects can be used to create iterators:
Functions that use yield are called generators
 A generator is a function that returns an iterator and can only be used for iterative operations. More simply, a generator is an iterator
 In the process of calling the generator to run, the function will pause and save all the current running information every time it encounters yield, return the value of yield, and continue to run from the current position the next time it executes the next() method


Advantages of multithreading

1. Using threads, you can put the tasks in the program that occupy a long time to the background for processing. 
2. The user interface can be more attractive. For example, if the user clicks a button to trigger the processing of some events, a progress bar can pop up to display the processing progress. 
3. The running speed of the program may be accelerated. 
4. In the implementation of some waiting tasks, such as user input, file reading and writing, network sending and receiving data, threads are more useful. In this case, we can release some precious resources, such as memory occupation and so on.

Thread classification

Kernel thread: created and revoked by the operating system kernel. 
User thread: a thread implemented in a user program without kernel support.

Thread module

Python 3 uses two standard libraries_ Thread (obsolete) and threading (recommended) provide support for threads

Thread synchronization

If multiple threads modify a data together, unexpected results may occur. In order to ensure the correctness of the data, multiple threads need to be synchronized. Simple Thread synchronization can be realized by using Lock and Rlock of Thread object. Both objects have acquire and release methods. For data that needs to be operated by only one Thread at a time, its operation can be placed between acquire and release methods

Thread priority Queue

Python's Queue module provides synchronized and thread safe Queue classes, including FIFO Queue, LIFO Queue, and PriorityQueue.
These queues implement lock primitives and can be used directly in multithreading. Queues can be used to achieve synchronization between threads.

What is Flask?

Flask is a lightweight Web application framework written in Python. Its WSGI toolbox uses Werkzeug, and the template engine uses jinja2. Flask uses BSD authorization. Two of these environment dependencies are Werkzeug and jinja2, which means that it does not need to rely on external libraries. For this reason, we call it lightweight framework.

Flash sessions use signature cookie s to allow users to view and modify session content. It records information from one request to another. However, to modify the session, the user must have the key flash secret_ key. 

Is there a tool that can help you find bug s in python and conduct static code analysis?

PyChecker is a static analysis tool for python code. It can help find bug s in python code and warn about the complexity and format of the code

Pylin is another tool that can check the coding standard

Programming problem

Binary conversion

The decimal system is the bridge. Use it first int(value,Hexadecimal digit)Convert to decimal, and then convert to other decimal
# Binary to decimal
# Convert octal to decimal
# Convert hex to decimal
# Convert decimal to binary
# Convert decimal to octal
# Convert decimal to hexadecimal
# Binary to hexadecimal

Type conversion

int()-Converts any data type to an integer type
float()-Convert any data type to float type
ord()-Convert characters to integers
hex()-Converts an integer to hexadecimal
oct()-Convert integer to octal
tuple()- This function is used to convert to tuples.
set()- This function is converted to set Return type after.
list()- This function converts any data type to a list type.
dict()- This function is used to convert sequential tuples (keys, values) into dictionaries.
str()- Used to convert an integer to a string.
complex(r eal,imag)-This function converts a real number to a complex number (real, image).

Generate random number

Generate a random floating-point number: a floating-point number between 0 and 1
Generates a random floating-point number with a specified range:[a,b]
    random.uniform(a,b) #If a=b, floating point number a is generated
Generate an integer within the specified range:[a,b]
Random number without end:start The default value is 0, step The default value is 1 and the range is[start,stop)
Scramble elements in a list
Get a random element from the sequence: the sequence includes list,tuple,String, etc
Get randomly from the specified sequence n Elements are returned as a fragment:
Get randomly from the specified sequence k Elements are returned as a fragment, sample Function does not modify the original sequence

Common built-in functions and their applications

Mathematical correlation

abs(a): Find the absolute value. abs(-1)  
max(iterable): seek list Maximum value. max([1,2,3])
min(iterable): seek list Minimum value. min([1,2,3]) 
sum(iterable): seek list The sum of the elements. sum([1,2,3]) #6
sorted(iterable): Sorting, return the sorted iterable. 
len(iterable): list length,len([1,2,3])
divmod(a,b): Get quotient and remainder. divmod(5,2) #(2,1)
pow(a,b): Gets the power. pow(2,3) #8
round(a,b): Gets the number of decimal places specified. a Represents a floating point number, b Represents the number of digits to be reserved. round(3.1415926,2) #3.14
range(a[,b]): Generate a a reach b Array of,Close left and open right. range(1,10) #[1,2,3,4,5,6,7,8,9]

Type conversion

int(str): Convert to int type
    int('1') #1
float(int/str): take int Convert type or character type to floating point type
    float('1') #1.0
str(int): Convert to character
    str(1) #'1'
bool(int): Convert to boolean type
    bool(0) #False 
    bool(None) #False
bytes(str,code): The format of the received string is the same as that of a byte to be returned
    bytes('abc','utf-8') #b'abc' 
    bytes(u'Reptile','utf-8') #b'\xe7\x88\xac\xe8\x99\xab'
list(iterable): Convert to list
    list((1,2,3)) #[1,2,3]
dict(iterable): Convert to dict
    dict([('a',1),('b',2),('c',3)]) #{'a':1,'b':2,'c':3}
tuple(iterable): Convert to tuple
    tuple([1,2,3]) #(1,2,3)
set(iterable): Convert to set
    set([1,4,2,4,3,5]) #{1,2,3,4,5} set({1:'a',2:'b',3:'c'}) #{1,2,3}
iter(iterable): Returns an iteratable object
    iter([1,2,3]) #<list_iterator object at 0x0000000003813B00>
enumerate(iterable): Returns an enumerated object
hex(int): Convert to hexadecimal
    hex(1024) #'0x400'
oct(int): Convert to octal
    oct(1024) #'0o2000'
bin(int): Convert to binary
    bin(1024) #'0b10000000000'
chr(int): Convert numbers to corresponding ASCI Code character
    chr(65) #'A'
ord(str): transformation ASCI Characters are corresponding numbers
    ord('A') #65

Functional correlation

reduce(func,sequence,initial): First, the first two elements of the sequence are passed to the function, and then the result obtained by the function and the third element are passed to the function as parameters;
    reduce(lambda x,y: x + y,range(0,101)) #Achieve 0 to 100 summation 5050;
filter(func,iterable): By judging function fun,Filter the qualified elements and return the list iterator
    list(filter(lambda x: x > 3,[3,4,1])) #[4]
map(func,*iterable): Take each element of one or more iterators as a function func Returns a parameter list iterator 
    list(map(lambda a,b: a+b,[1,2,3,4],[5,6,7])) #[6,8,10]
zip(*iterable): Merge one or more iterators to return a list nested metagroup iterator.
    list(zip([1,2,3],[4,5,6])) #[(1,4),(2,5),(3,6)]
    dict(zip([1,2,3],[4,5,6])) #{1:4,2:5,3:6}
reversed(sequence): An iterator that generates an inverted sequence. 
    list(reversed('abc')) #['c','b','a']
type(): Returns the type of an object.
id():  Returns the unique identification value of an object.
hash(object): Returns the of an object hash Value, with the same value object Have the same hash Value. 
    hash('python') #7070808359261009780
isinstance(): Judge whether an object is an instance of this class.
issubclass(): Determine whether a class is a subclass of another class.
eval(): Executes an expression or string as an operation. eval('1+1') #2
exec(): implement python sentence. exec('print("Python")') #Python
help(): Call the built-in help system of the system.
globals(): Returns the dictionary of the current global variable.
next(iterator[,default]): Receive an iterator and return the value in the iterator. If set default,When the elements in the iterator are traversed, the output default Content.

Judge leap year

def func(yearNum):
    if yearNum % 400 == 0 or (yearNum % 4 == 0 and yearNum % 100 != 0):
        print(f'{yearNum}It's a leap year')
        print(f'{yearNum}Year is not a leap year')

Multiplies each element of a list and returns a new sequence

list(map(lambda x:x*x,list_1)) #[1,4,9,16,25,36]

Standardize the list of English names according to the rules of capitalized initial letters and lowercase subsequent letters

list(map(lambda x:x[0].upper()+x[1:].lower(),list_1))   # ['Adam','Lisa','Bart']

How to round a number to three decimal places


What kinds of string formatting are commonly used?

'%s%d%f' % ('a',1,0.1)

Fibonacci sequence

x,y = 0,1
while x < 100:
    x,y = y,x + y
def fib(n):
    index,a,b = 0,0,1
    while index < n:
        yield b
        a,b = b,a+b
        index += 1

multiplication table

for i in range(1,10):
    for x in range(1,i + 1):
        print(f'{x}*{i}={x * i}',end=' ')
lis = ['%s%s=%s'%(i,j,ij) for i in range(1,10) for j in range(i,10)]

Numerical exchange with one line of code

a = 1 
b = 2
a,b = b,a

Using slicing operation, a trim() function is implemented to remove the spaces at the beginning and end of the string (there are multiple spaces)

def trim(str):
    if str[0] == ' ':
        return trim(str[1:])
    elif str[-1:] == ' ':
        return trim(str[:-1])
        return str

Please use iteration to find the minimum and maximum values in a list and return a tuple

def findMaxMin(list_temp):
    min,max = list_temp[0],list_temp[0]
    for x in list_temp:
        if x > max:
            max = x
        elif x < min:
            min = x
    return (min,max)

How to generate [1,4,9,16,25,36,49,64,81100] with one line of code

[i*i for i in range(1,11)]
print(list(map(lambda x: pow(x,2),range(1,11))))

One line of code to delete duplicate values in the list


Calculate the number of uppercase letters in a file

with open('file name') as f:
    for i in
        if i.isupper():

How to delete a file using python?

import os
file = r'D:\test.txt'
if os.path.exists(file):
    print('delete success')
    print('no such file:%s' % file)

How to generate a random number?

import random
print(random.random())          # Used to generate a random number of characters from 0 to 1: 0 < = n < 1.0
print(random.randint(1,1000))  # Used to generate an integer within a specified range

Using random module, write a 6-digit random verification code, which contains letters and numbers (random)

import random
s = ''
for i in range(6):
    num = random.randint(0,9)
    alpha1 = chr(random.randint(65,90))     #A-Z
    alpha2 = chr(random.randint(97,122))    #a-z
    ret = random.choice([num,alpha1,alpha2])
    s += str(ret)

Please write a function to convert the IP address into an integer The conversion rule is:
10           00001010
3            00000011
9            00001001
12           00001100

Then combine the above binary to calculate the decimal result: 0000100 000000 11 00001001 000011100 = ?
def func(x):
    lis = x.strip().split('.')
    li = [bin(int(i)) for i in lis]
    li2 = [i.replace('0b',(10-len(i))*'0') for i in li]
    return int(''.join(li2),2)
ret = func('')

Tuple unpacking and grouping

def func_01(a,*args):
    print('a=',a)  # a= 1
    print('args=',args)  # args= (2,3,4)
    print('Unpacking *args = ',*args)  # Unpacking * args = 2 3 4
def func_02(*args):
    print('func02 args=',args)  # func02 args= ((2,3,4),)
    print('func02 *args = ',*args)  # func02 *args =  (2,3,4)
def func_03(args):
    print('func03 args=',args)  # func03 args= (2,3,4)
    print('func03 *args=',*args)  # func03 *args= 2 3 4

How to change "1,2,3" into ['1', '2', '3']


How to change '123' into ['1', '2', '3']


How to change ['1', '2', '3'] into [1,2,3]

print([int(x) for x in ['1','2','3']])

How to turn '123' into [1,2,3]


List set dictionary sorting

user_list = [
    {'name': 'Zhang San','age': 22,'title': 'Test Engineer'},
    {'name': 'Li Si','age': 24,'title': 'Development Engineer'},
    {'name': 'Wang Wu','age': 21,'title': 'Test Engineer'}
user_list.sort(key=lambda x: x['age'])  # Ascending order
user_list.sort(key=lambda x: x['age'],reverse=True)  # Descending order

Find the first character that appears only once and return its position

def findchar(temp):
    for i in temp:
        if temp.count(i)==1:
            return i, temp.index(i)
temp = 'hellobaby'
print('The first character to appear once is{},Location is{}'.format(m,n))

The number of times a number appears in the array is more than half the length of the array

def func(temp):
    for i in temp:
        if temp.count(i) > len(temp)/2:
            return i

Give a 32-bit signed integer and reverse the integer

-123 > -321

123 > 321

12300 > 321

def func(val):
    if val > 0:
        temp = str(val)[-1::-1]
        temp = int(str(val)[-1:0:-1])

The registration of known achievements is divided into: {"a": "90-100", "B": "80-89", "C": "60-79", "d": "0-59 '}

(1)Randomly generate 20 integers in the range of 0-100

(2)Classified by level, output format:{'A':[90,99,91],'B':[80,81,89],'C':[70,79,60],'D':[0,58,59]}

import random
res_dict = {}
list_a = []
list_b = []
list_c = []
list_d = []
for i in range(20):
    n = random.randint(0, 100)
    if 90 <= n <= 100:
    elif 80 <= n <= 89:
    elif 60 <= n <= 79:
res_dict["A"] = list_a
res_dict["B"] = list_b
res_dict["C"] = list_c
res_dict["D"] = list_d

Replace spaces in a string with "% 20"

str_data = 'wex cws asda asdw we'
# Mode 1
res = str_data.replace(' ', '%20')
#Mode 2
list_data = list(str_data)
for i in range(len(list_data)):
    if list_data[i] == ' ':
        list_data[i] = '%20'
res = ''.join(list_data)

One line of code realizes 1-100 summation, one line of code realizes 1-100 odd summation, and one line of code realizes 1-100 even summation

sum(range(1, 101))
sum(range(1, 101, 2))
sum(range(2, 101, 2))

One line of code realizes 1-100 even summation in at least 5 ways

from functools import reduce
print(reduce(lambda x,y : x + y , range(2,101,2)))

Please use recursive function to realize factorial of 10: 10987 one

def factorial(num):
    if num <= 1:
        return 1
    return num * factorial(num-1)

Without changing the data arrangement structure in the list, find the number Li = [- 100,1,3,2,7,6120121140,23411,99243,33,85,56]

li = [-100, 1, 3, 2, 7, 6, 120, 121, 140, 23, 411, 99, 243, 33, 85, 56]
mid = (max(li) + min(li)) / 2
res = abs(li[0] - mid)
result = None
for i in li:
    curr_min = abs(i - mid)
    if curr_min < res:
        res = curr_min
        result = i

What day of the year

Function: enter a certain day of a certain month of a certain year to judge the day of the year
 Version: 4.0
from datetime import datetime
def is_leap_year(year):
    judge year Is it a leap year
    Yes: Return true
    No: return false
    is_leap = False
    if (year % 400 == 0) or ((year % 4 == 0) and (year % 100 != 0)):
        is_leap = True
        return is_leap
def main():
    input_date_str = input('Please enter a date( yyyymmdd)')
    input_date = datetime.strptime(input_date_str ,'%Y%m%d')
    year = input_date.year
    month = input_date.month
    day =
    # #Collection containing 30 days of the month
    # _30_days_month_set = {4,6,9,11}
    # _31_days_month_set = {1,3,5,7,8,10,12}
    #Create dictionary
    month_day_dict = {1:31,2:28,3:31,4:30,5:31,6:30,7:31,8:31,9:30,10:31,11:30,12:31}
    days = 0
    days += day
    for i in range(1,month):  #Starting from 1
        days += month_day_dict [i]
    if month > 2 and is_leap_year(year) :
        days += 1
    print('This is{}The second day of the year{}Oh, my God.'.format(year,days))
if __name__=='__main__':

Bubble sorting

list = [7,2,1,6,5,3,8,4]
for x in range(0,len(list)):
    for y in range(0,len(list)):
        if list[x] < list[y]:
            list[x],list[y] = list[y],list[x]

Binary search

# Returns the index of x in arr, or - 1 if it does not exist
def binarySearch(arr, l, r, x):
    if r >= l:
        mid = int(l + (r - l) / 2)
        # Middle position of element adjustment
        if arr[mid] == x:
            return mid
            # If the element is smaller than the element in the middle, you only need to compare the element on the left
        elif arr[mid] > x:
            return binarySearch(arr, l, mid - 1, x)
            # If the element is larger than the element in the middle, you only need to compare the element on the right
            return binarySearch(arr, mid + 1, r, x)
        # non-existent
        return -1
# Test array
arr = [2, 3, 4, 10, 40]
x = 10
result = binarySearch(arr, 0, len(arr) - 1, x)
if result != -1:
    print("The index of the element in the array is %d" % result)
    print("Element not in array")

Quick sort

def partition(arr,low,high): 
    i = ( low-1 )         # Minimum element index
    pivot = arr[high]     
    for j in range(low , high): 
        # The current element is less than or equal to pivot 
        if   arr[j] <= pivot: 
            i = i+1 
            arr[i],arr[j] = arr[j],arr[i]
    arr[i+1],arr[high] = arr[high],arr[i+1] 
    return ( i+1 ) 
# Arr [] -- > sort array
# Low -- > start index
# High -- > end index
# Quick sort function
def quickSort(arr,low,high): 
    if low < high:
        pi = partition(arr,low,high) 
        quickSort(arr, low, pi-1) 
        quickSort(arr, pi+1, high) 
arr = [10, 7, 8, 9, 1, 5] 
n = len(arr) 
print ("Sorted array:") 
for i in range(n): 
    print ("%d" %arr[i])

Find the result

def multipliers():
    return [lambda x:i*x for i in range(4)]
print([m(2) for m in multipliers()])     #[6,6,6,6]
print([ i % 2 for i in range(10) ])  # [0,1,0,1,0,1,0,1,0,1]
print([ i  for i in range(10) ])     # [0,1,2,3,4,5,6,7,8,9]
print([ 10 % 2])   # [0]
1 or 2      #1
1 and 2     #2
1 < (2==2)  #False
1 < 2 == 2  #True
print(int('111', 2))  #7
num = 5
def func():
    num = 10
    print('func', num)
def func2():
    print('func2', num)
func()    # 10
func2()    # 5

Topics: Python