Python face question

Source: Internet
Author: User
Tags garbage collection generator shallow copy

How does 1.Python manage memory?

A: From three aspects, the reference counting mechanism of an object, two garbage collection mechanism, three memory pool mechanism

I. Reference counting mechanism for objects

Python uses reference counting internally to keep track of objects in memory, and all objects have reference counts.

case where the reference count increases:

    • An object is assigned a new name
    • Put it in a container (such as a list, a tuple, or a dictionary)

Decrease in reference count:

    • Destroying an object alias display using the DEL statement
    • Reference is out of scope or is being re-assigned

The Sys.getrefcount () function can get the current reference count of an object

In most cases, the reference count is much larger than you would guess. For non-volatile data, such as numbers and strings, the interpreter shares memory in different parts of the program to conserve memory.

Second, garbage collection

    • When the reference count of an object is zeroed, it is disposed of by the garbage collection mechanism.
    • When two objects A and B reference each other, the DEL statement reduces the reference count of A and B and destroys the name used to refer to the underlying object. However, because each object contains an application to other objects, the reference count is not zeroed and the object is not destroyed. (which results in a memory leak). To solve this problem, the interpreter periodically executes a loop detector that searches for loops of inaccessible objects and deletes them.

Three, 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.

    • Pymalloc mechanism. To speed up the execution of Python, Python introduces a memory pooling mechanism for managing the application and release of small chunks of memory.
    • All objects less than 256 bytes in Python Use the allocator implemented by Pymalloc, while large objects use the system malloc.
    • For Python objects, such as integers, floating-point numbers, and lists, there are separate pools of private memory that do not share their pools of memory among objects. That is, if you allocate and release a large number of integers, the memory used to cache these integers can no longer be assigned to floating-point numbers.

2. What is a lambda function? What good is it?

A: Ambda defines an anonymous function, and lambda does not increase the efficiency of the program, only makes the code more concise.

For example:

A=lambdax,y:x+ya (3,11)

3.Python How to implement the conversion of tuple and list?

A: Using the tuple and list functions directly, type () can determine the type of the object

4. Write a Python code to delete the repeating element in a list

For:

1. Using Set function, set (list)

2, using the dictionary function,

>>>a=[1,2,4,2,4,5,6,5,7,8,9,0]

>>> b={}

>>>b=b.fromkeys (a)

>>>c=list (B.keys ())

>>> C

5. Programming with Bubble sort

Array = [1, 2, 5, 3, 6, 8, 4]for I in range (len (array)-1, 0,-1): For    J in range (0, i):        if array[j] > Array[j + 1]:            array[j], array[j + 1] = array[j + 1], array[j]print array

6.Python How to copy an object? (Assignment, shallow copy, deep copy difference)

A: Assignment (=) is the creation of a new reference to the object, and modifying any of the variables will affect the other.

Shallow copy: Creates a new object, but it contains a reference to the containing item in the original object (if one of the objects is modified by reference) {1, the full slice method; 2, the factory function, such as list (); the copy () function of the 3,copy module}

Deep copy: Creates a new object and recursively copies the objects it contains (modifies one, the other does not change) {Copy module's deep.deepcopy () function}

#-*-Coding:utf-8-*-import Copy
list = [1, 2, 3, 4, [' A ', ' B ']] #原始对象b = list #赋值, reference to the object, still pointing to LISTC = Copy.copy (list) #对象拷贝, shallow copy (element remains a shared reference) d = Copy.deepcopy (list) #对象拷贝, deep copy list.append (5) #修改对象listlist [4].append (' C ') #修改对象list中的 [' A ', ' B '] Array object Print (' list = ', list) print (' B = ', b) print (' C = ', c) print (' d = ', D)

7. Introduce the usage and function of except?

Answer: Try...except...except ... [Else ...] [Finally ...]

Executes the statement under try, and if an exception is thrown, the execution skips to the except statement. An attempt is performed on each except branch order, and if the exception that is thrown matches the exception group in except, the corresponding statement is executed. If all except do not match, the exception is passed to the next highest-level try code that calls this code.

If the statement under try executes normally, the else block code is executed. If an exception occurs, it will not execute

If a finally statement exists, it is always executed.

What is the function of the pass statement in 8.Python?

A: The pass statement will not take any action, typically as a placeholder or create a placeholder program.

9. Describe the use of the range () function under Python?

A: Lists a set of data that is often used to iterate through the data in a for X in range () Loop:

>>> Range (1,5) #代表从1到5 (not including 5) [1, 2, 3, 4]>>> Range (1,5,2) #代表从1到5, Interval 2 (not including 5) [1, 3]>>> range (5) #代表从0到5 (not including 5) [0, 1, 2, 3, 4]

10. How do I use Python to query and replace a text string?

A: You can use the sub () function in the RE module or the SUBN () function to query and replace, and the Subn () method performs the same effect as a sub (), but it returns a two-dimensional array, including the replacement of the new string and the total number of replacements

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

A: the match () function in the RE module only checks to see if it matches the beginning of the string, while search () scans the entire string.

12. What is the difference between,<.*> and <.*?> when matching HTML tags with python?

A: The term is called greedy match (<.*>) and non-greedy match (<.*?>)

For example:

Import res = "

How to generate random numbers in 13.Python?

Answer: Random module

Random integer: Random.randint (A, B): Returns a random integer x,a<=x<=b

Random.randrange (Start,stop,[,step]): Returns a random integer in the range (Start,stop,step), excluding the end value.

Random real number: Random.random (): Returns the floating-point number from 0 to 1

Random.uniform (A, B): Returns the floating-point number in the specified range.

14. Is there a tool that can help find Python bugs and perform static code analysis?

A: Pychecker is a static analysis tool for Python code that helps you find bugs in Python code and warns you about the complexity and format of your code.

Pylint is another tool that can be codingstandard checked

15. How do I set a global variable in a function?

A: The workaround is to insert a global declaration at the beginning of the function:

def f ()

Global X

16. The difference between a single quote, double quotation marks, and three quotation marks

A: Single and double quotation marks are equivalent, if you want to wrap, you need a symbol (\), three quotation marks can be directly wrapped, and can contain comments

If you want to represent let's go this string

Single quote: S4 = ' let\ ' Go '

Double quotes: S5 = "Let's Go"

S6 = ' I realy like ' python '! '

17. Explain the difference between the generator (generator) and the function, and implement and use simple generator?

The main difference between a generator and a function is that the function returns Avalue, and the generator yield a value marks or remembers point of the yield at the same time to facilitate the resumption of execution from the mark points at the next call. Yield causes a function to be converted to a generator, which in turn returns an iterator.

The difference between 18.os.path and Sys.path?

The OS module is responsible for the interaction between the program and the operating system, provides access to the underlying interface of the operating system, and the SYS module is responsible for the interaction between the program and the Python interpreter, providing a series of functions and variables for manipulating the Python runtime environment.

Python face question

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.