You must prepare the Python programmer interview questions in advance! (Answer and resolution), python programmer

Source: Internet
Author: User
Tags how to use git python decorator asymmetric encryption

You must prepare the Python programmer interview questions in advance! (Answer and resolution), python programmer

You must prepare for these questions before releasing "Python programmer interview". After the article, in response to the strong requirements of the majority of programmers and friends, xiaobian compiled a reference answer to the essential questions for the Python programmer interview, hoping to help programmers who are preparing for a job change. If you have any questions about the answer, please leave a message to discuss it.

Xiaobian divides these interview questions into four categories:

What )? How )? Difference and practice ).

What?

1. What is Python?

Python is a programming language that includes objects, modules, threads, exception handling, and automatic memory management. You can add a comparison with other languages. The following are the key points to answer this question:

A. Python is an interpreted language, and python code does not need to be compiled before it is run.

B. Python is a dynamic type language. When declaring a variable, you do not need to describe the type of the variable.

C. Python is suitable for Object-Oriented Programming because it supports defining classes by combination and inheritance.

D. in Python, functions are the first type of objects.

E. Python code writing is faster, but the running speed is slower than that of the compiling language.

F. Python is widely used and is often used as a "glue language" to help other languages and components improve running conditions.

G. With Python, programmers can focus on designing algorithms and data structures without having to deal with the underlying details.

2. What is Python introspection?

Python introspection is a kind of capability of python. It enables programmers to get the python-like object type when running programs written in object-oriented languages. Python is an interpreted language. It provides programmers with great flexibility and control.

3. What is PEP 8?

PEP8 is a programming specification that provides some suggestions on how to make your program more readable.

4. What are pickling and unpickling?

The Pickle module reads any Python objects, converts them into strings, and uses the dump function to dump them into a file. This process is called pickling. The process of extracting the original Python object from the stored string file is called unpickling.

5. What is a Python decorator?

The Python modifier is a special change in Python that makes it easier to modify functions.

6. What is a Python namespace?

In Python, all names exist in a single space, which exists in the space and is operated-this is the namespace. It is like a box where every variable name corresponds to an object. When querying a variable, the corresponding object is searched from the box.

7. What are dictionary derivation and list derivation?

They are the syntax structure that allows you to easily create dictionaries and lists.

8. What is a Lambda function?

This is an anonymous function that is often used for a single expression in code.

9. * args, ** kwargs? What are parameters?

If we are not sure how many parameters will be passed into the function, or if we want to pass parameters in the form of a list and a group in the function, we need to use * args; if you do not know how many keyword parameters you want to input to the function, or want to input the dictionary value as a keyword parameter, you need to use ** kwargs.

10. What is a Pass statement?

Pass is a statement that is not executed in Python. In complex statements, if a place needs to be temporarily white, it is often used as a placeholder.

11. What is unittest?

In Python, unittest is a unit test framework in Python. It supports shared building, automatic testing, code suspension during testing, and iteration of different tests into a group.

11. What is the constructor?

Constructor is a mechanism for implementing the iterator. The implementation of its function depends on the yield expression. In addition, it is similar to a common function.

12. What is doc string?

The document string in Python is called docstring. in Python, it is used to generate documents for functions, modules, and class annotations.

13. What is a negative index?

Sequence indexes in Python can be positive or negative. If it is a positive index, 0 is the first index in the sequence, and 1 is the second index. If it is a negative index, (-1) is the last index and (-2) is the second to last index.

14. What are modules and packages?

In Python, modules are a way to build programs. Every Python code file is a module and can reference other modules, such as objects and attributes.

A folder containing many Python code is a package. A package can contain modules and subfolders.

15. What is garbage collection?

In Python, object reference count is used to solve Memory leakage and automatic garbage collection is implemented based on reference count.

16. What is CSRF?

CSRF is an attack that spoofs client requests. CSRF stands for Cross Site Request Forgery, meaning Cross-Site Request Forgery.

How?

1. How to make your program more readable?

Add non-leading spaces, empty rows, and consistent names as appropriate.

2. How is Python interpreted?

Python is an interpreted language and its source code can be directly run. The Python interpreter converts the source code into an intermediate language, and then translates the source code into a machine code and then executes it.

3. How to copy an object in Python?

If you want to copy an object in Python, you can use copy. copy () or copy. deepcopy () most of the time (). But not all objects can be copied.

4. How to delete an object using Python?

Use the function OS. remove ("file ")

5. How to convert a number into a string?

You can use the built-in function str () to convert a number to a string. If you want octal or hexadecimal numbers, you can use oct () or hex ().

6. How does Python perform memory management?

Python memory management is managed by private heap space. All Python objects and data structures are in a private heap. The programmer has no permission to access the heap. Only the interpreter can operate on the heap. The memory allocated to the heap space of Python is implemented by the Python memory management module. Its core API provides some methods to access this module for programmers to use. Python has its own garbage collection system, which recycles and releases unused memory so that it can be used by other programs.

7. How to convert tuple and list?

Initialize the tuple class with list as the parameter, and the tuple type is returned.

Initialize the list class with tuple as the parameter and return the list type.

8. How to generate a random number in Python?

In python, the module used to generate random numbers is random. Before use, import. The following example can be used as appropriate:

Random. random (): generates a random floating point number between 0 and 1.

Random. uniform (a, B): generate a floating point number between [a, B]

Random. randint (a, B): generate an integer between [a, B]

Random. randrange (a, B, step): in the specified set [a, B), a random number is obtained based on step.

Random. choice (sequence): Randomly retrieves an element from a specific sequence. The sequence can be a string, list, or tuples.

9. How to set a global variable in a function

To assign a value to a global variable in a function, you must use the global statement. The global VarName expression tells Python that VarName is a global variable, so that Python will not find this variable in a local namespace.

10. How does Python implement the singleton mode? How to Implement the other 23 Design Patterns in python?

The Singleton mode has four main methods: __new _, shared attributes, decorator, and import.

The other 23 design patterns can be divided into creation, structure, and behavior patterns.

The creation mode provides the instantiation method and the corresponding object creation method for the appropriate condition.

Structured patterns are usually used to process the relationships between entities so that these entities can work together better.

Behavior mode, used for communication between different entities, providing easier and more flexible communication methods for communication between entities.

The implementation of each mode can write code according to its characteristics (limited space, here is not an example)

11. how to determine whether a ring exists in a one-way linked list?

First, repeat the Link Table to check whether there is a ring in the linked list. If the program enters an infinite loop, a space is required to store the pointer. When traversing the new pointer, it compares it with the stored old pointer. If there is the same pointer, the linked list has a ring, otherwise, the new pointer is saved and then read down until NULL is met, which indicates that the linked list has no loops.

12. How to traverse an unknown internal folder?

The following methods are commonly used: OS. path. walk (), OS. walk (), listdir

13. How to partition and split tables in the mysql database?

Table sharding can be performed in three ways: mysql cluster, custom rules, and merge storage engine.

There are four types of partitions:

RANGE partition: multiple rows are allocated to the partition based on the column values in a given continuous interval.

LIST partition: similar to partitioning by RANGE, the difference is that LIST partition is selected based on the column value matching a value in a discrete value set.

HASH partition: select a partition based on the return value of a user-defined expression. This expression uses the column values of the rows to be inserted into the table for calculation. This function can contain any expressions that are valid in MySQL and generate non-negative integer values.

KEY partitioning: similar to HASH partitioning, the difference is that KEY partitioning only supports computing one or more columns, and the MySQL server provides its own HASH function. One or more columns must contain integer values.

14. How to optimize the query command?

A. Try to avoid full table scanning. First, we should consider creating a cable on the columns involved in where and order.

B. Avoid null value judgment on the field in the where clause as much as possible! = Or <> operator to avoid using or join conditions, or using parameters in the where clause, and performing expressions or function operations on fields. Otherwise, a canonicalized scan is performed.

C. do not perform functions, arithmetic operations, or other expression operations on the left side of "=" in the where clause. Otherwise, the system may not be able to correctly use indexes.

D. when an index field is used as a condition, if the index is a composite index, the system must use the first field in the index as the condition to ensure that the index is used, otherwise, the index will not be used.

E. in many cases, you may consider replacing in with exists.

F. use numeric fields whenever possible

G. Try to replace char/nchar with varchar/nvarchar

H. Do not use select * from t anywhere, replace "*" with a specific field list, and do not return any fields that are not used.

I. Try to use table variables instead of temporary tables.

J. Avoid frequent creation and deletion of temporary tables to reduce the consumption of system table resources.

K. Avoid using the cursor as much as possible because the efficiency of the cursor is poor.

L. set nocount on at the beginning of all stored procedures and triggers, and set nocount off at the end

M. Avoid large transaction operations as much as possible to improve the system concurrency capability.

N. Avoid returning a large amount of data to the client as much as possible. If the data volume is too large, consider whether the corresponding requirements are reasonable.

15. How to understand open source?

Open Source: open source code. Open source was born in the software industry. It not only represents the opening of software source code, but also means freedom, sharing and full use of resources. Open source is a kind of spirit, a culture, and now has become the trend of the development of the software industry.

16. How to understand the MVC/MTV framework?

MVC divides Web applications into three layers: Model (M), controller (C), and view (V). They are connected in a plug-in and loosely coupled manner. Essentially, the MTV model is the same as the MVC model. It is also designed to maintain loose coupling between components, but its definition is somewhat different.

17. How does MSSQL deadlock occur?

The following are four necessary conditions for deadlock:

Mutex: A process schedules the resources allocated to it. That is, a resource is only occupied by one process within a period of time. If there are other processes requesting resources at this time, the requester can only wait until the processes occupying the resources are released after use.

Request and retention conditions: the process has maintained at least one resource, but has made new resource requests. The resource has been occupied by other processes. At this time, the request process is blocked, however, you cannot release other resources that you have obtained.

Non-deprivation condition: resources obtained by a process cannot be deprived before they are used up. They can only be released by themselves when they are used up.

Loop wait condition: When a deadlock occurs, there must be a process-a loop chain of resources, that is, a process set {P0, P1, P2 ,···, p0 in Pn} is waiting for resources occupied by P1; P1 is waiting for resources occupied by P2 ,......, Pn is waiting for resources occupied by P0.

18. How does one prevent SQL injection?

During program development, you do not pay attention to writing SQL statements and filtering special characters. As a result, the client can submit some SQL statements through the global variable POST and GET for normal execution. SQL injection is generated. The following is a precaution:

A. filter out some common database operation keywords or use system functions to filter.

B. Set Register_globals to off in the PHP configuration file.

C. When writing SQL statements, try not to omit small quotation marks (the one above the tab key) and single quotation marks.

D. Improve database naming skills. Some important fields are named based on program characteristics, which are hard to be guessed.

E. encapsulate common methods to avoid direct leakage of SQL statements

F. Enable the PHP security mode: Safe_mode = on;

G. Enable magic_quotes_gpc to prevent SQL injection.

H. control error message: Disable the error message and write the error message to the system log.

I. Use mysqli or pdo preprocessing.

19. How can xxs be prevented?

XSS vulnerabilities are difficult to detect, but we still need to avoid them for the sake of WEB security:

For reflective and storage XSS, the server and the front-end should be prevented together to parse and escape user input data. For front-end development, escape is a good choice, perform regular identification on data URI content to prevent users from entering non-displayed information.

For dom xss, XSS is caused by user input. Therefore, at the front-end, you must pay special attention to the user input source and perform string escape for possible XSS operations.

20. How to generate a shared key? How can we prevent man-in-the-middle attacks?

The key is generated by using the global configuration command: for keys that cannot be output, <crypto key generate rsa label {label string }, the output key is <crypto key generate rsa exportable label {label string}>. Label is optional. If no tag is specified, the key name will be hostname. domain-name.

The following measures can be taken to prevent man-in-the-middle attacks:

A. Strengthen network infrastructure through dynamic ARP detection, DHCP Snooping, and other control operations

B. encrypted transmission

C. Use CASBs (cloud Access Security Proxy)

D. Create RASP (Real-time application self-protection)

E. Disable self-signed certificates

F. Force SSL pinning

G. Install DAM (database activity monitoring)

21. How to manage different versions of code?

For version management. You can give an example of how to use Git (or other tools) for tracking.

Difference

1. What are the differences between arrays and elements?

An array is called a list in python. The list can be modified, but the tuples cannot be modified. If there is only one element in the tuples, a comma is added to the element. The query method for tuples and lists is the same. Tuples can only be readable and cannot be modified. If the data in the program cannot be modified.

2. What is the difference between _ new _ and _ init?

_ Init _ is called after the instance object is created, and then some initial values of the object property are set.

_ New _ is called before the instance is created, because its task is to create an instance and then return the instance, which is a static method.

That is, __new _ is called before _ init _, And the return value (Instance) of __new _ is passed to the first parameter of the _ init _ method, then _ init _ sets some parameters for the instance.

3. What is the difference between single-underline and double-stroke in Python?

The member variables starting with "single underline" are called protection variables, meaning that only class objects and subclass objects can access these variables themselves;

"Double underline" begins with a private member, which means that only the class object can access the data, and even the subclass object cannot access the data.

4. What is the difference between shallow copy and deep copy?

In python, object assignment is actually an object reference. The child object is not copied, so the original data changes, the child object changes, and the deep copy contains the copy of the Self-object in the object, therefore, changes to the original object will not cause any child element changes in the deep copy.

5. What are the differences between the singleton for using the decorator and the singleton for using other methods?

The Import method changes the class itself, the new method, but shares all instance objects with the property to generate a new object each time. As a pseudo-Singleton, the shared attribute method instantiates many identical attributes. Therefore, the decorator method is the most practical.

6. What is the difference between multi-process and multi-thread?

A. In short, a program has at least one process and at least one thread.

B. The thread division scale is smaller than the process, which makes the multi-threaded program highly concurrent.

C. In addition, the process has independent memory units during execution, and multiple threads share the memory, which greatly improves the program running efficiency.

D. There is a difference between a thread and a process during execution. Each Independent thread has a program running entry, sequence execution sequence, and program exit. But the thread cannot be executed independently. It must exist in the application and the application provides multiple thread execution control.

E. Logically, multithreading means that multiple execution parts can be executed simultaneously in an application. However, the operating system does not view multiple threads as multiple independent applications to implement process scheduling, management, and resource allocation. This is an important difference between processes and threads.

7. What is the difference between select and epoll?

A. the select implementation requires you to constantly poll all fd sets until the device is ready, during which sleep and wakeup may alternate multiple times. Epoll also needs to call epoll_wait to continuously poll the ready linked list. During this period, sleep and wake up may alternate multiple times. However, when the device is ready, epoll calls the callback function, put the ready fd in the ready linked list and wake up the sleep process in epoll_wait. Although both sleep and alternate, the select statement traverses the entire fd set while being "Awake, when epoll is "Awake", you only need to judge whether the ready linked list is empty, which saves a lot of CPU time.

B. for each select call, the fd set must be copied once from the user State to the kernel state, and the current must be hung once in the device waiting queue, while epoll only needs to be copied once, in addition, the current is only mounted to the waiting queue once (at the beginning of epoll_wait, note that the waiting queue here is not a device waiting queue, but a waiting queue defined inside epoll ). This can also save a lot of expenses.

8. What is the difference between TCP and UDP? What is the difference between edge trigger and horizontal trigger?

A. Basic differences:

Connection-based and connectionless

TCP requires a large amount of system resources and a small amount of UDP;

Simple UDP program structure

Stream mode (TCP) and datagram mode (UDP );

TCP ensures data correctness and UDP may cause packet loss.

TCP ensures data order, But UDP does not

B. Differences in programming

The socket () parameters are different.

UDP Server does not need to call listen and accept

Use the sendto/recvfrom function to send and receive UDP data

TCP: The address is determined at connect/accept.

UDP: Specify the address information each time in the sendto/recvfrom function.

UDP: the shutdown function is invalid.

9. HTTP connection: What is the difference between get and post?

In a GET request, the requested data will be appended to the URL? Splits the URL and transmits data. Multiple parameters are connected. The URL encoding format uses ASCII encoding instead of uniclde, that is, all non-ASCII characters must be encoded before transmission.

POST request: the POST request places the requested data in the packet body of the HTTP request package. The above item = bandsaw is the actual data transmission.

Therefore, the GET request data is exposed in the address bar, while the POST request does not.

10. What is the difference between varchar and char?

The char length is fixed. No matter how much data you store, it will be fixed. Varchar can be a variable in length, but it needs to add 1 character to the total length, which is used to store the location. Therefore, the processing speed of char is much faster than that of varchar, but it does not have much storage space, but the char type can be used for speed requirements, otherwise, you can use the varchar type.

11. What is the difference between B-tree indexes and hash indexes?

Due to its special structure, Hash indexes have high retrieval efficiency. Index retrieval can be performed at a time, unlike B-Tree indexes that need to be retrieved from the root node to the branch node, the Hash index query efficiency is much higher than that of B-Tree indexes. But there are also the following obvious disadvantages:

A. the Hash index only supports "=", "IN" and "<=>" queries, and does not support range queries.

B. Hash indexes cannot be used to avoid data sorting.

C. Hash indexes cannot be queried using some index keys.

D. the Hash index cannot avoid table scanning at any time.

E. The performance of Hash indexes is not necessarily higher than that of B-Tree indexes when a large number of Hash values are equal.

12. What is the difference between primary key and unique?

A. the domain/domain group used as the Primary Key cannot be null, while the Unique Key can.

B. A table can have only one Primary Key, and multiple Unique keys can exist at the same time.

C. In logic design, the Primary Key is generally used as the record identifier in the logic design. This is also the original intention of setting the Primary Key, while the Unique Key is only used to ensure the uniqueness of the domain/domain group.

13. What is the difference between ecb and cbc?

ECB: it is a basic encryption method. ciphertext is divided into blocks with the same group length (which cannot be supplemented), encrypted separately, and output the ciphertext one by one.

CBC: it is a loop mode in which the ciphertext of the previous group and the plaintext of the current group are differentiated or operated before encryption. This aims to increase the difficulty of cracking. The encryption results of ECB and CBC are different. The two modes are different. In addition, CBC adds an initialization vector to the first cryptographic block operation.

14. What is the difference between symmetric encryption and asymmetric encryption?

Symmetric encryption requires the same key encryption algorithm for encryption and decryption. Due to its high speed, symmetric encryption is usually used when the message sender needs to encrypt a large amount of data. Therefore, symmetric encryption is also called key encryption.

Asymmetric encryption algorithms require two keys: public keys and private keys. A public key is a pair of private keys. If a public key is used to encrypt data, only the corresponding private key can be used for decryption. If a private key is used to encrypt data, only the corresponding public key can be decrypted.

15. What is the difference between Xrange and range?

Range ([start,] stop [, step]) generates a Sequence Based on the range specified by start and stop and the step size set by step. Xrange is used in the same way as range. The difference is that the generated object is not a list object, but a generator. Xrange is much better than range to generate a large number sequence, because it does not need to open up a large memory space. Range directly generates a list object, while xrange does not directly generate a list, but returns a value in each call.

16. What is the difference between OS and sys modules?

The former provides a convenient way to use operating system functions. The latter provides access to the variables used or maintained by the interpreter and functions that interact with the interpreter.

17. What is the difference between NoSQL and relational databases?

A. SQL data has tables with specific structures, while NoSQL is more flexible and scalable. The storage method can be saved as JSON documents, hash tables, or other methods.

B. in SQL, you must define the table and field structure before adding data. For example, you can define the table's primary key (primary key), index (index), trigger (trigger ), stored procedure. The table structure can be updated after it is defined, but it will become complicated if there is a large structure change. In NoSQL, data can be added anywhere at any time without the need to define tables.

C. If you need to add external join data in SQL, the normalization method is to add a foreign key to the original table to associate the External table. In addition to this standardized external data table practice in NoSQL, we can use the following non-standardized method to directly store external data in the original data set to improve query efficiency. The disadvantage is also obvious. It will be troublesome to update the reviewer's data.

D. You can use JOIN table links in SQL to query data in multiple relational data tables using a simple query statement. At present, NoSQL does not provide a JOIN-like Query Method to query data in multiple datasets. Therefore, most NoSQL uses non-standard data storage to store data.

E. SQL does not allow you to delete external data that has been used. NoSQL does not have this concept of strong coupling and can delete any data at any time.

F. If multiple tables in SQL need to be updated in the same batch, that is, if one of the tables fails to be updated, other tables cannot be updated successfully. This scenario can be controlled through transactions, and transactions can be committed after all commands are completed. NoSQL does not have the transaction concept. Each dataset operation is atomic.

G. Under the same level of system design, because NoSQL skips the consumption of JOIN queries, the theoretical performance is superior to SQL.

Practice

This kind of practical operation questions are rich and diverse, and the following categories are common:

1. Add missing code

For example:

def print_directory_contents(sPath): import os           for sChild in os.listdir(sPath):      sChildPath = os.path.join(sPath,sChild)  if os.path.isdir(sChildPath):   print_directory_contents(sChildPath)  else:   print sChildPath

2. What is the output result of the following code? Please explain.

For example:

list1 = [10, 'a']list2 = [123]list3 = [10, 'a']

The new default list is created only once when the function is defined. When extendList is called without specifying a specific parameter list, the value of this list will be used later. This is because expressions with default parameters are calculated when the function is defined, not when called.

3. Can the following code be run? Please explain?

For example:

Can run. When the key is missing, the DefaultDict class is executed. The dictionary instance will automatically instantiate this series.

4. Sort functions by execution efficiency and verify that their answers are correct.

For example:

Sort by execution efficiency from high to low: f2, f1, and f3. To prove that the answer is correct, you should know how to analyze the performance of your code. Python has a good program analysis package to meet this requirement.

......

The above are common questions and answers for the Python interview compiled by Alibaba Cloud for the reference of the majority of Python programmers, hoping to provide a little help.

I would like to recommend the python book order for you to learn the article:

The Python book order will not meet

In your opinion, the Python team should have this book order.

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.