Python interview question Summary

Source: Internet
Author: User

Python interview question Summary

I think the interview questions can quickly improve my skills

1. How does Python perform memory management?

Python memory management has three main mechanisms: reference counting mechanism, garbage collection mechanism, and memory pool mechanism.

A. Reference count

When an object is assigned a new name or an object is put into a container (list, tuples, or dictionary), the reference count of this object increases.
When del is used to display the destroyed object or the reference exceeds the limit or is assigned a value again, the reference count of this object is reduced.
You can use the sys. getrefcount () function to obtain the current reference count of an object. In most cases, the reference count is much larger than we guess. For immutable data (numbers and strings), the interpreter shares memory in different parts of the program to save memory.

B. Garbage Collection

When the reference count of an object is zero, it will be disposed of by the garbage collection mechanism.
When two objects a and B reference each other, the del statement can reduce the reference count of a and B and destroy the name used to reference the underlying object. However, because each object contains an application for other objects, the reference count is not zero and the object is not destroyed. (Resulting in Memory leakage ). To solve this problem, the interpreter periodically executes a loop detector to search for loops of inaccessible objects and delete them.

C. Memory Pool Mechanism

Python provides a garbage collection mechanism for memory, but it puts unused memory into the memory pool instead of returning it to the operating system.
1. Pymalloc mechanism. To accelerate the execution efficiency of Python, Python introduces a memory pool mechanism to manage the application and release of small memory blocks.
2. All objects smaller than 256 bytes in Python use the Allocator implemented by pymalloc, while large objects use the system's malloc.
3. Python objects, such as integers, floating-point numbers, and lists, all have their own private memory pools, and objects do not share their memory pools. That is to say, if you allocate and release a large number of integers, the memory used to cache these integers cannot be distributed to floating point numbers.

2. What is a lambda function? What are its advantages?

Lambda expressions are usually used when a function is needed, but you don't want to bother naming a function, that is, anonymous functions.
Lambda functions: the primary purpose is to give pointers to short callback functions.
Lambda [arguments]: expression
>>> A = lambda x, y: x + y
>>> A (3, 11)

3. How does one convert tuple and list in Python?

Simply use the tuple and list functions. type () can be used to determine the object type.

4. Write a piece of Python code to delete duplicate elements in a list.

Set can be used here. For the usage of set, refer to operations of the Python set type.

5. How to copy an object in Python? (Assignment, shortest copy, and deep copy)

A value (=) is a new reference of an object. modifying any variable affects the other.
Shallow copy: Creates a new object, but it contains references to the items contained in the original object (if one object is modified by reference, the other will also be changed) {1, full slicing method; 2, factory functions, such as list (); 3, copy () function of the copy module}
Deep copy: Creates a new object and Recursively copies the objects it contains (modifying one of them will not change) {copy module's deep. deepcopy () function}

6. What are the usage and functions of ipvt?

Try... Else T... Else T... [Else…] [Finally…]
Execute the statement in try. If an exception is thrown, the execution process jumps to the limit t statement. Execute the command in sequence for each branch. If the exception is matched with the exception group in branch T, execute the corresponding statement. If none of the except T matches, the exception will be passed to the top-level try code that calls this code next.
If the statement in try is executed normally, the else block code is executed. If an exception occurs, it will not be executed.
If a finally statement exists, it is always executed.

7. What is the difference between match () and search () in Python?

Match (pattern, string [, flags]) in the re module, and check whether the start of string matches pattern.
In the re module, research (pattern, string [, flags]) searches for the first matching value of pattern in string.
>>> Print (re. match ('super', 'superstition '). span ())
(0, 5)
>>> Print (re. match ('super', 'insuperable '))
None
>>> Print (re. search ('super', 'superstition '). span ())
(0, 5)
>>> Print (re. search ('super', 'insuperable'). span ())
(2, 7)

8. When matching HTML tags with Python, <. *> and <. *?> What is the difference?

The term is greedy match (<. *>) and non-Greedy match (<. *?> )
For example:

Test
<. *>: Test
<. *?> :

 

9. What is the output of the following code? Give your answer and explain

 

class Parent(object):    x = 1class Child1(Parent):    passclass Child2(Parent):    passprint Parent.x, Child1.x, Child2.xChild1.x = 2print Parent.x, Child1.x, Child2.xParent.x = 3print Parent.x, Child1.x, Child2.x
Output:

 

 

1 1 11 2 13 2 3
What makes you confused or surprised is that the output of the last row is 3 2 3 rather than 3 2 1. Why does the value of Parent. x change the value of Child2.x, but the value of Child1.x does not change at the same time?
The key to this answer is that in Python, class variables are internally processed as dictionaries. If the name of a variable is not found in the dictionary of the current class, the ancestor class (for example, parent class) will be searched) until the referenced variable name is found (if the referenced variable name is neither found in its own class nor in its ancestor class, an AttributeError exception is thrown ).
Therefore, setting x = 1 in the parent class makes the value of class variable X in referencing the class and any of its subclasses 1. This is because the output of the first print statement is 1 1.
Then, if any of its child classes overwrites the value (for example, we execute the statement Child1.x = 2), then the value is only changed in the Child class. This is why the output of the second print statement is 1 2 1.
Finally, if the value is changed in the Parent class (for example, we execute the statement Parent. x = 3). This change will affect the value of any subclass that has not overwritten this value (in this example, the affected subclass is Child2 ). This is why the third print output is 3 2 3.

 

10. What will the following code output?

 

list = ['a', 'b', 'c', 'd', 'e']print list[10:]
Answer
The above code will output [] without causing an IndexError.
As expected, attempting to access a member that exceeds the list index value will cause IndexError (for example, accessing the list [10] in the above list). However, attempts to access a list with the number of members in the list as the starting index will not cause IndexError, and will only return an empty list.
One annoying small problem is that it causes bugs and is difficult to trace because it does not cause errors during runtime.

 

11. What is the output of the following code? Tell your answer and explain it?

 

def extendList(val, list=[]):    list.append(val)    return listlist1 = extendList(10)list2 = extendList(123,[])list3 = extendList('a')print list1 = %s % list1print list2 = %s % list2print list3 = %s % list3

 

How will you modify the extendList definition to produce the expected results?

The output of the above Code is:

list1 = [10, 'a']list2 = [123]list3 = [10, 'a']
Many people mistakenly think that list1 should be equal to [10] And list3 should be equal to ['a']. It is believed that the list parameter will be set to its default value [] each time extendList is called.
However, what actually happens is that the new default list is only created once when the function is defined. When extendList is not called by the specified list parameter, it uses the same list. This is why when a function is defined, the expression is calculated using the default parameter, rather than called.
Therefore, list1 and list3 are the same list of operations. '''''List2 is an independent list created by the Operation (it uses its own empty list as the value of the list ''' parameter ).
The extendList function can be defined as follows. However, when no new list parameter is specified, a new list is always started, which is more likely to be the expected behavior.
Def extendList (val, list = None): if list is None: list = [] list. append (val) return list uses this improved implementation, and the output will be: list1 = [10] list2 = [123] list3 = ['a']

 

12. What is output by the following program?

 

list = [ [ ] ] * 5list  # output?list[0].append(10)list  # output?list[1].append(20)list  # output?list.append(30)list  # output?
Okay, the first line of code is the first time I saw it. The first line outputs [[], [], [], [], [], A list containing five empty lists, and the second line outputs [[10], [10], [10], [10], [10], I can only explain that these five lists point to the same list, so modifying any of the other four will change. You can use list [0] = 10 to disconnect a connection.

 


 

Related Article

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.