The Python foundation of the interview

Source: Internet
Author: User
Tags generator shallow copy

1. Describe the explanatory and compiled programming language?
compile-language :

    • 1, pre-compilation: The source code is written, before execution, the compiler will directly compile the source code into machine code, compile only once, compile the time according to the corresponding operating environment to generate machine code, the system environment is different, compiled executable file is also different;
    • 2. Link: The machine code of each module and the dependent library are concatenated to generate the executable file. Advantages: High execution efficiency; disadvantage: cross-platform type is poor, development efficiency is low (modify code needs to be precompiled); Representative language: C,C++,SIWFT

interpreted language :

    • No compilation is required, only translated into machine language when running the program.
    • Translate once every time you run it.
    • Advantages: Good cross-platform (the premise is to install the interpreter), the development of high efficiency (modified code directly modified);
    • Cons: Inefficient execution (requires compilation once each time it is run);
    • Representative languages: JavaScript, Python, PHP, Perl;

2. What are the types and features of the Python interpreter?

    • CPython, Ipython, PyPy, Jython, IronPython

3, bit and byte relationship?

    • bit: bit, smallest unit of computer, one binary number 0 or 1;
    • BYTE: 1byte=8bit;

4, B, B, KB, MB, GB of the relationship?

    • 1 gb= MB; 1MB = 1024kb;1kb=1024b;1b=8b

5. Please list at least 5 PEP8 specifications?

    • Use 4 spaces for each level of indentation;
    • The function name uses the all lowercase method, can use the underline;
    • A constant name can be underlined by using all uppercase methods;
    • The maximum number of characters for all row limits is 79, and a backslash can be used for line breaks;

6. List the differences between Python2 and Python3?

    • Print difference: py2 Direct use print ‘a‘ , py3 use print(‘a‘) ;
    • Range difference: Returns the range(n) list in Py2, PY3 returns the iterator, saves the memory;
    • Coding differences: Py2 using ascii,py3 utf-8 encoding;
    • String and byte string: Py2 Unicode represents a string, str denotes a byte string, py3 in str denotes a string, bytes represents a byte string;
    • The input () function, Py2, is in the raw_input() py3.input()

7, anonymous function?

    • You need to use a function but not to name it.

      foo = lambda x:x**2foo()# 等价于def foo(x):    return x**2

8, the role of pass?

    • No action will be taken
    • Guaranteed Format Complete
    • Make sure the semantics are correct

9, *arg and **kwarg role?

    • Used primarily for function definitions, passing an indefinite number of arguments to a function.
    • *args: A variable number of parameter lists used to send a non-key value pair to a function
    • **kwargs: Allows you to pass variable-length key-value pairs as arguments to a function

10, is and = = Difference

    • is a comparison operator in the Python standard operator that is used to compare the value of two objects for equality
    • Compare to determine if the memory address pointed to is the same.

11. A brief description of Python's depth copy

    • Shallow copy: Only the immutable elements () are copied str,tuple , the memory address reference is made to the element () in the variable container, and lst,dict once the elements in the container change, the reference will change;
    • Deep copy: Re-open space to save all elements without shared memory references.

12, Python garbage collection mechanism? 2

    • 1, Reference counting algorithm . When there are 1 variables that hold a reference to the object, for example a=20,b=a , the reference count for this object is added to 1. When using Del to delete the object to which the variable is pointing, if the reference count of the object is not 1, such as 3, then only the reference count will be reduced by 1, that is, to 2, when the Del is called again, 1, and if you call 1 del again, the object is actually deleted;
    • 2, mark the clearing mechanism . Wait until there is no free memory from the register and the reference on the stack to start, traverse the object as a node, a reference to the composition of the graph, put all accessible objects, mark, and then sweep the memory space, all unmarked objects released. The disadvantage is that the entire heap memory must be scanned sequentially.
    • 3, generational technology . Divides all memory blocks in the system into different collections, which are "generations", according to their survival time. The frequency of garbage collection decreases as the "generation" of survival time increases, and the survival time is usually measured by several garbage collections. The newly created objects are assigned to the young generation, when the total number of young linked lists reaches the upper limit, the Python garbage collection mechanism is triggered, the objects that can be recycled are recycled, and the objects that are not recycled are moved to the Middle Ages, and so on, the objects in the old age are the objects that have survived the longest. Even within the life cycle of the entire system.

13. What are the mutable types and immutable types of python?

    • 1, immutable type (number, string, tuple, immutable set): Do not support in-situ modification, can only re-request memory space;
    • 2, mutable type (list, dictionary, mutable collection): Can be modified in situ, the container memory address will not change.

14. List common built-in functions?

dir(__builtin__)  #  win列出所有内置函数abs()pow(x,y)  # x**yround()dir()str()set()list()max()min()id()getattr()setattr()

15, a line of code implementation 9*9 multiplication table

ele = ''for x in range(1,10):    for y in range(1,x+1):        ele= ele + '%sx%s=%s' % (x,y,x*y)+ '\t'    ele+='\n'print(ele)# 一行代码实现print('\n'.join('\t'.join(['%sx%s=%s' % (x,y,x*y) for y in range(1,x+1)]) for x in range(1,10)))

16. What is the list of common modules?

Time, DateTime, collection, Re, OS, random, JSON, pickle, Hashlib, subprocess.

17. What is the difference between match and search for re?

    • Match: Start with the first bit on the left;
    • Search: Match from left to right.

18. What is the difference between greedy and non-greedy matching of regular expressions?

    • The default greedy match, the more matches the better, the non-greedy match is appended after the pattern ? !

      In [16]: m = re.match('\d+',s)In [17]: mOut[17]: <_sre.SRE_Match object; span=(0, 2), match='12'>In [18]: m = re.match('\d+?',s)In [19]: mOut[19]: <_sre.SRE_Match object; span=(0, 1), match='1'>

19. How to realize the [‘1’,’2’,’3’] change [1,2,3] ?

# 原地修改lst = ['1', '2', '3']for k,v in enumerate(lst):    lst[k] = int(v)print(lst)# 创建新列表l1 = [int(x) for x in lst]print(l1)# map_reduce原地修改lst = list(map(lambda x:int(x),lst))print(lst)

20. How to generate with one line of code [1,4,9,16,25,36,49,64,81,100] ?

print([i**2 for i in range(1,11)])

21, talk about your understanding of closures?

    • 1, the function defines the nesting function;
    • 2. The outer function returns a reference to the inner nested function;
    • 3. The inner layer function refers to the variable of the outer function.

22, __new__ and the __init__ difference?

    • __new__is called before the instance is created, because its task is to create an empty instance and then return it, which is a static method;
    • __init__is called after the instance object has been created, you can set some initial values for the object properties.

23, do you know several design patterns?

24. Encoding and decoding have you ever known?

    • Encoding: converting characters into binary according to specific rules;
    • Decoding: Converting binary code into characters according to corresponding decoding rules;
    • The coding rules are:

      ascii       1byte   gbk         2byteunicode     2byte   包含与所有字符的映射关系,内存中的通用格式utf8        可变长,汉字3bytes,字母1byte,传输时候可以用utf8编码

25. List comprehension and generator's merits and demerits are deduced.

    • is an iterative object that can be used for loops;
    • The algorithm stored by the generator, when the sequence is larger, the generator can save memory, but the generator is a one-time, after the end of the iteration will be automatically destroyed

26. What is an adorner? What should I do if I want to decorate after a function?

    • The function of the original function is extended without changing the original function, and the adorner is essentially a closure function.

27, handwritten one using the adorner implementation of the single case mode?

def singleton(cls):    instance = {}    def _singleton(*args):        if cls not in instance:            # 调用类的init方法,采用dict模式其他类可以重复使用            instance[cls] = cls(*args)          return instance[cls]    return _singleton@singletonclass People(object):    def __init__(self,name, age):        self.name=name        self.age=age    def add(self):        passs = People('alex',23)s1 = People('kate',28)print(s==s1)  # True

28. What is the difference between a single case using an adorner and a single case using another method?

    • Code reuse

29. Handwritten regular email address

pattern = '[1-9a-z][email protected](qq|126|163|gmail|foxmail|yahoo)\.com'import rem = re.match(pattern,s)print(m.group())

30, multi-process and multi-threaded differences? What is CPU intensive for?

31, the introduction of the next process, why is faster than the thread?

    • Process, the user program level to achieve task switching, and threads are the interpreter level;
    • The Gevent module implements pseudo-multithreading.

The Python foundation of the interview

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.