Follow + star, learn new Python skills every day
From the Internet, intrusion and deletion
1: What is the difference between Python lists, tuples, and dictionaries?
This question should be asked often, and we explain it in detail here.
-
List (List), Python's list is actually a dynamic array, stored in a continuous memory block, the complexity of random access is O(1), inserting and deleting elements will cause the movement of the memory block, time The complexity is O(n). At the same time, it is a mutable object. When we assign a value to the list, we only get its memory address. If we need to copy all the contents of the list to another variable, we need to use copy (shallow copy) and deepcopy (depth copy). copy).
-
Tuple, Python's tuple is an immutable data structure, which is essentially an array. Because it is an immutable object, the length of the Tuple is constant when it is created, so we cannot add or remove elements from it. However, the objects contained within a Tuple are mutable. When we assign a variable containing a tuple to another variable, we actually re-apply for a new memory space in memory to create a new tuple.
-
Dictionary (Dict), Python's dictionary is a hash table, a data structure that is directly accessed according to the key-value pair (Key, Value). There is not much analysis about the hash function here, you can understand it yourself. If the dictionary produces a hash collision, that is, when the Key encounters a duplicate. Python will calculate the next candidate position through the open addressing method, and repeatedly test to ensure that the generated hash value will not collide. Dictionaries, like lists, are also mutable objects. Copy (shallow copy) and deepcopy (deep copy) are also required to copy content.
2: How to output a string or number in reverse order?
String reverse order, we can use Python's slice to reverse the string, refer to the following code:
str1 = "长风几万里,吹度玉门关"print(str1[::-1])
Slice parameter format: [start_index: stop_index: step]
If we do not fill in the start and end position parameters of the slice, then the default is to take the entire content of the string. When the step parameter (step length) is negative, the string will automatically take values from right to left, -1 is to take values in sequence, then naturally It's in reverse order.
We can also output the numbers in reverse order through the principle of slicing.
# 正整数的情况number = 10002new_number = int(str(number)[::-1])# 负整数的情况number = -10002new_number = int('-{0}'.format(str(abs(number))[::-1]))
3: Talk about Python's memory management mechanism
Python has a built-in garbage collection mechanism, and reference counting is part of this mechanism.
In the Pyhton source code, the two macros Py_INCREF(op) and Py_DECREF(op) are actually used to increment and decrement the reference count.
When an object is created, assigned, passed by parameters, and before the function returns, its reference count value (ob_refcnt) may be incremented by 1 (INC), and it keeps accumulating.
When the object variable goes out of scope, the value of the reference count is decremented by 1 (DEC).
When an object's reference count is reduced to 0 (ob_refcnt is 0), Py_DECREF(op) will call the object's " destructor " (__del__) to release it from memory.
4: What are Session, Cookie, Token?
Session is a concept where information is stored on the server side.
Cookie is an implementation of Session, and the information is stored in the client (browser).
Because of the stateless nature of the HTTP protocol, we need to establish a credential between the browser and the server to identify the user's identity and detailed information. This credential can be either Cookie or Token.
When the user logs in successfully, we can generate a session information on the server with his credentials and save it in a file, database or memory. Usually, the session will have a session id.
Because the session id is needed to access the server-side session information, usually, we store the session id in the cookie.
In fact, the cookie information returns the session id or other additional information to the client after the user logs in to generate the session information, which is stored in the local file by the client.
When the browser initiates a request to the server, it will access the server with the session id in the cookie. The server finds the stored session information according to the session id. If the information can be found and the content is correct, the access is deemed valid.
In addition to storing the session id, cookies can also store other non-sensitive information (such as user nicknames, avatars, etc.), which are provided to the browser for direct use without having to get it from the server every time.
Regarding Token, it is actually used more in RESTAPI-based services.
Its authentication mechanism is that when the user logs in, the server calculates a Token information and stores it on the server and returns it to the client. The content usually includes the user id, current timestamp, signature and other information.
Tokens are generally stored in localStorage, cookie, or sessionStorage on the client side. The server is generally stored in the database.
When the client requests the server again, it will get the Token information locally and put it in the headers. When the server receives the request, it will automatically go to the headers to get the Token for parsing to identify the user.
5: What is the difference and function of GET and POST?
There is no difference between GET and POST in essence, and the HTTP protocol does not specify the length limit of the data transmitted by GET and POST.
The only restrictions may exist on the server-side server and browser.
Usually in Nginx or various WebServer service programs, there is a limit to define the maximum length of GET and POST transmission.
The length limit of the data submitted by GET usually depends on the browser, and the limit of each browser is different.
In the HTTP protocol, there is actually no relationship between what method is used and how data is transmitted, in most WebServers. The data submitted by GET and POST are actually in the BODY area. We can transfer files through GET or POST.
The reason why GET is usually defined to get data and POST to submit data is because GET requests are idempotent, while POST requests are not.
Idempotency means that once and multiple requests for a resource should have the same side effects. In simple terms it means that multiple requests to the same URL should return the same result.
Based on the principle of idempotency, when we use GET to add, modify and delete data, there will be side effects, because GET will automatically try to retry when the network condition is not good, increasing the risk of duplicating data operations. And using it to get data will not have such a risk, because even if we request a resource 1 million times, it will still not change.
This question depends on the technical level of the interviewer. If the interviewer is willing to chat with you more deeply, then you can answer this way. If the interviewer has some standard answers in his mind, it is recommended to only answer GET for obtaining data and POST for submitting data.
In addition, the DELETE method is actually idempotent. Even if you delete 1 million times, the data will only be deleted once.
6: What is a Python decorator.
Python's decorator is essentially a function, and its use is to allow other functions to add functions related to the decorator function without making too many code changes.
Let's first look at the implementation and application of decorators.
Above we have implemented a minimalist Python decorator, which prints logs at the beginning and end of the fun1 function. Through this example, we can find that Python's decorator actually simplifies the calling code for us. If no decorator is used, then The above code can be written like this.
The above code will explicitly call the func1 function through the log function, which is not easy to understand, and also destroys the order of code calls, which is not elegant. If I need to add more than 10 decorators to the front of fun1, I have to write this call relationship more than ten times, which is basically a disaster in terms of reading comprehension.
Python's decorators are usually used but not limited to the following situations.
-
log print
-
Performance Testing
-
database transaction processing
-
permission check
-
Cache processing
To sum up, the use of the Pyhton decorator is to allow us to better reuse code, and to adopt a code structure that is more in line with human understanding when implementing the same functional code.
In fact, Python's decorator is AOP programming (slicing-oriented) in the JAVA language.
7: Python's concepts of global locks, processes, threads, and coroutines
Python's global lock is a compromise made to ensure thread safety. Simply put, no matter how many CPU cores are, only one thread can run at the same time. For IO-intensive operations, multi-threading is barely usable. If it is CPU-intensive, Python's multi-threading is almost useless.
If you want to take advantage of the multi-core CPU, you can use processes. The multiprocessing module in Pyhton handles this problem. Each computing task will start a separate Python process, allowing the task to run in an independent interpreter environment to improve computing efficiency.
The concept of coroutine is that threads and processes will generate a lot of performance overhead when switching between CPU user mode and kernel mode.
In this case, the concept of coroutines or micro-threads came into being.
After Python 3.5, use the async/await keyword to handle coroutines.
Its advantages are:
-
There is no overhead of switching between threads.
-
There is no thread lock mechanism, because there is only one thread, there is no shared variable locking, which further improves the efficiency.
8: List comprehensions and dictionary comprehensions
# 列表推导list1 = [i for i in range(5)]# 字典推导dict1 = {k:v for k,v in dict.items()}# 集合推导set1 = {x*2 for x in [1,2]}
List comprehension, dictionary comprehension, and set comprehension are all features of Python, and dictionary comprehension is available after Python 2.7.
The functions of these three derivation methods are to construct another new data sequence structure from the existing data sequence, which is necessary from the perspective of code readability and convergence, avoiding complicated and trivial codes. spelling.
9: Generator
# 构造生成器x = (i for i in range(10))# 输出x<generator object <genexpr> at 0x10e9d40c0>
We can see from the above code that the format of the generator is very similar to the list comprehension format. The only difference is that the square brackets are replaced by parentheses. The object generated by the generator is no longer a list, but a generator object.
The function of the generator is that when we want to generate a very long sequence, we don't necessarily need to use it immediately, so we don't need to open up a large memory space when we generate it again, but declare an object first and tell it I need a large memory space, but I can generate them one by one when I use them. There is a word for this in other languages called "lazy evaluation".
We can directly use the for loop to traverse the generator object and retrieve the values in turn.
Let’s talk about these 9 interview questions first. Due to space limitations, we actually don’t talk about it in depth, because if we want to talk about it in depth, every knowledge point here can take a whole chapter to talk about in detail, but I I think everyone can understand and practice more details based on these knowledge points.
For the interviewer, the programmer interview is actually not how many questions you can answer correctly, but whether the quality of the questions you answer is in the part that he agrees with. The more detailed we master each knowledge point, the part that the other party agrees with. The more, the higher the success rate.
Long press or scan the QR code below to get free Python open courses and hundreds of gigabytes of learning materials packaged and organized by the big guys , including but not limited to Python e-books, tutorials, project orders, source code, etc.
▲ Scan the QR code - get it for free
Recommended reading
Breaking the world record! Automatic mine sweeping with Python! Artifact! A Python efficient crawler framework that is easier to use than requests! Eight schemes for implementing timed tasks in Python! Python makes progress bar, there are so many methods