Python pen questions (2017 Latest) Python interview questions

Source: Internet
Author: User
Introduction do you want to find a Python development job? Then you may have to prove that you know how to use Python. The following questions involve many Python-related skills. Want to find a Python development job? Then you may have to prove that you know how to use Python. The following questions involve many Python-related skills. the focus is on the language itself, not a specific package or module. Every question can be expanded into a tutorial, if possible. Some problems may even involve multiple fields.

I have not prepared any questions that are as difficult as these questions. if you can answer them easily, hurry up and get a job! Below isLatest Python exam question (2017).

Question 1

What is Python? You can compare it with other technologies in the answer (we also encourage this ).

Answer

The following are some key points:

Python is an interpreted language. This means that, unlike C and C, Python code does not need to be compiled before running. Other interpreted languages include PHP and Ruby.

Python is a dynamic type language. it means that you do not need to describe the type of a variable when declaring a variable. You can directly write code such as x = 111 and x = "I'm a string" without any errors.

Python is ideal for object-oriented programming (OOP) because it supports defining classes through composition and inheritance ). Python does not have access specifiers (access specifier, similar to public and private in C ++). The basis for this design is "everyone is an adult ".

In Python, a function is the first class object (first-class objects ). This means that they can be specified to Variables. a function can return both the function type and the function can be used as input. Class is also the first class object.

Python code writing is faster, but the running speed is slower than that of the compiling language. Fortunately, Python allows extensions written in C language. Therefore, we can optimize the code and eliminate bottlenecks, which is usually implemented. Numpy is a good example. it runs very fast because many arithmetic operations are not actually implemented through Python.

Python is widely used-network applications, automation, scientific modeling, big data applications, and so on. It is also often used as a "glue language" to help other languages and components improve running conditions.

Python makes difficult things easier, so programmers can focus on the design of algorithms and data structures without having to deal with the underlying details.

Question 2

Add missing code

Def print_directory_contents (sPath): "" This function accepts the folder name as the input parameter and returns the path of the file in the folder and the path of the file in the folder. "" # Supplemental code

Answer

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

Pay special attention to the following points:

The naming rules should be uniform. If you can see the naming conventions in the sample code, follow the existing standards.

Recursive functions must be recursive and terminated. Make sure you understand the principles. Otherwise, you will be faced with call stacks ).

We use the OS module to interact with the operating system. at the same time, the interaction mode can be cross-platform. You can write the code as sChildPath = sPath + '/' + sChild, but this error may occur on Windows.

It is very valuable to be familiar with basic modules, but don't stick to your head. remember that Google is your mentor and friend at work.

If you do not understand the expected functions of the code, ask a question.

Stick to the KISS principle! Keep it simple, but you can understand it in your mind!

Why do you ask this question:

This section describes the basic knowledge of the user's interaction with the operating system.

Recursion is really easy to use.

Question 3

Read the following code and write the final values from A0, A1 to.

A0 = dict(zip(('a','b','c','d','e'),(1,2,3,4,5)))A1 = range(10)A2 = [i for i in A1 if i in A0]A3 = [A0[s] for s in A0]A4 = [i for i in A1 if i in A3]A5 = {i:i*i for i in A1}A6 = [[i,i*i] for i in A1]

Answer

A0 = {'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}A1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]A2 = []A3 = [1, 3, 2, 5, 4]A4 = [1, 2, 3, 4, 5]A5 = {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}A6 = [[0, 0], [1, 1], [2, 4], [3, 9], [4, 16], [5, 25], [6, 36], [7, 49], [8, 64], [9, 81]]

Why do you ask this question:

List parsing saves a lot of time and is also a learning obstacle for many people.

If you read the code, you may be able to write down the correct values.

Some of the code is intentionally written. This is because some of the people you work with will have geeks.

Question 4

Python and multi-threading ). Is this a good idea? Lists some methods for running Python code in parallel.

Answer

Python does not support true multithreading. Multi-threaded packages are provided in Python. However, it is not a good idea to use multi-threaded packages if you want to speed up code through multiple threads. In Python, there is something called Global Interpreter Lock (GIL), which ensures that only one of your multiple threads is executed at any time. The thread execution speed is very fast, which may lead you to mistakenly think that the thread is executed in parallel, but it is actually executed in turn. After GIL is processed, the execution overhead is increased. This means that if you want to improve the code running speed, using the threading package is not a good method.

However, there are still many reasons for us to use the threading package. If you want to execute some tasks at the same time without considering the efficiency problem, it is completely okay to use this package, and it is also very convenient. But in most cases, this is not the case. you want to outsource the multi-threaded part to the operating system (by enabling multiple processes ), or some external programs that call your Python code (such as Spark or Hadoop), or other code called by your Python code (for example, you can call the C function in Python, used to process the multi-threaded jobs with high overhead ).

Why is this question raised?

Because GIL is A mixed account (A-hole ). Many people spend a lot of time trying to find bottlenecks in their own multi-threaded code until they understand the existence of GIL.

Question 5

How do you manage different versions of code?

Answer

Version management! When asked this question, you should be excited and even tell them how you use Git (or another tool you like best) to track your correspondence with grandma. I prefer to use Git as the version control system (VCS), but there are other options, such as subversion (SVN ).

Why do you ask this question:

Because there is no version control code, it is like coffee without a Cup. Sometimes we need to write some one-time scripts that can be discarded at will. in this case, no version control is required. However, if you are dealing with a large amount of code, it is advantageous to use a version control system. Version control can help you track who has performed any operations on the code library, discover new bugs, manage different versions and releases of your software, and share source code among team members; deployment and other automated processing. It allows you to roll back to the version before the problem occurs. this is really great. There are other good functions. What's so amazing!

Question 6

What will the following code output:

def f(x,l=[]):    for i in range(x):        l.append(i*i)    print lf(2)f(3,[3,2,1])f(3)

Answer:

[0, 1][3, 2, 1, 0, 1, 4][0, 1, 0, 1, 4]

ER?

The first function call is very obvious. the for loop adds 0 and 1 to the empty list l successively. L is the name of the variable, pointing to a list stored in the memory. The second function call creates a new list in a new memory. L then it points to the newly generated list. Then add 0, 1, 2, and 4 to the new list. Great. The result of the third function call is somewhat strange. It uses the old list stored in the previous memory address. That's why the first two elements are 0 and 1.

If you don't understand, try to run the following code:

l_mem = []l = l_mem           # the first callfor i in range(2):    l.append(i*i)print l             # [0, 1]l = [3,2,1]         # the second callfor i in range(3):    l.append(i*i)print l             # [3, 2, 1, 0, 1, 4]l = l_mem           # the third callfor i in range(3):    l.append(i*i)print l             # [0, 1, 0, 1, 4]
Question 7

What does monkey patching mean? Is this a good practice?

Answer

"Monkey patch" refers to changing the behavior of functions or objects after they are defined.

For example:

import datetimedatetime.datetime.now = lambda: datetime.datetime(2012, 12, 12)

In most cases, this is a bad practice-because the behavior of functions in the code library is best to be consistent. The reason for the monkey patch may be for testing. The mock package is very helpful for this purpose.

Why is this question raised?

Correct answers to this question indicate that you have a certain understanding of unit test methods. If you mention that you want to avoid "monkey patching", it means that you are not the kind of programmer who is fond of code. (this is the kind of person in the company. it's terrible to work with them ), it focuses more on maintainability. Remember the KISS principle code? Correct answers also indicate that you understand how Python works at the underlying layer and how functions are stored and called.

In addition, if you have not read the mock module, it is really worth the time to read it. This module is very useful.

Question 8

What do these two parameters mean: * args, ** kwargs? Why should we use them?

Answer

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. The args and kwargs identifiers are conventional usage. you can also use * bob and * billy, but this is not appropriate.

The following is an example:

def f(*args,**kwargs): print args, kwargsl = [1,2,3]t = (4,5,6)d = {'a':7,'b':8,'c':9}f()f(1,2,3)                    # (1, 2, 3) {}f(1,2,3,"pythontab")           # (1, 2, 3, 'pythontab') {}f(a=1,b=2,c=3)              # () {'a': 1, 'c': 3, 'b': 2}f(a=1,b=2,c=3,zzz="hi")     # () {'a': 1, 'c': 3, 'b': 2, 'zzz': 'hi'}f(1,2,3,a=1,b=2,c=3)        # (1, 2, 3) {'a': 1, 'c': 3, 'b': 2}f(*l,**d)                   # (1, 2, 3) {'a': 7, 'c': 9, 'b': 8}f(*t,**d)                   # (4, 5, 6) {'a': 7, 'c': 9, 'b': 8}f(1,2,*t)                   # (1, 2, 4, 5, 6) {}f(q="winning",**d)          # () {'a': 7, 'q': 'winning', 'c': 9, 'b': 8}f(1,2,*t,q="winning",**d)   # (1, 2, 4, 5, 6) {'a': 7, 'q': 'winning', 'c': 9, 'b': 8}def f2(arg1,arg2,*args,**kwargs): print arg1,arg2, args, kwargsf2(1,2,3)                       # 1 2 (3,) {}f2(1,2,3,"pythontab")              # 1 2 (3, 'pythontab') {}f2(arg1=1,arg2=2,c=3)           # 1 2 () {'c': 3}f2(arg1=1,arg2=2,c=3,zzz="hi")  # 1 2 () {'c': 3, 'zzz': 'hi'}f2(1,2,3,a=1,b=2,c=3)           # 1 2 (3,) {'a': 1, 'c': 3, 'b': 2}f2(*l,**d)                   # 1 2 (3,) {'a': 7, 'c': 9, 'b': 8}f2(*t,**d)                   # 4 5 (6,) {'a': 7, 'c': 9, 'b': 8}f2(1,2,*t)                   # 1 2 (4, 5, 6) {}f2(1,1,q="winning",**d)      # 1 1 () {'a': 7, 'q': 'winning', 'c': 9, 'b': 8}f2(1,2,*t,q="winning",**d)   # 1 2 (4, 5, 6) {'a': 7, 'q': 'winning', 'c': 9, 'b': 8}

Why is this question raised?

Sometimes, we need to input the unknown number of parameters or keyword parameters to the function. Sometimes, we also want to store parameters or keyword parameters for future use. Sometimes, only to save time.

Question 9

What does the following mean: @ classmethod, @ staticmethod, @ property?

Background

These are all decorator ). The decorator is a special function that either accepts a function as an input parameter and returns a function, or accepts a class as an input parameter and returns a class. @ Tag is the syntactacactic sugar, which allows you to describe the target object in a simple and easy-to-read manner.

@my_decoratordef my_func(stuff):    do_thingsIs equivalent todef my_func(stuff):    do_thingsmy_func = my_decorator(my_func)

On this website, you can find teaching materials about how the decorators work.

Real answer

The objects @ classmethod, @ staticmethod, and @ property decorator use functions defined in the class. The following example shows their usage and behavior:

Class MyClass (object): def init (self): self. _ some_property = "properties are nice" self. _ some_other_property = "VERY nice" def normal_method (* args, ** kwargs): print "calling normal_method ({0}, {1 })". format (args, kwargs) @ classmethod def class_method (* args, ** kwargs): print "calling class_method ({0}, {1 })". format (args, kwargs) @ staticmethod def static_method (* args, ** kwargs): print "calling static_method ({ 0 },{ 1 })". format (args, kwargs) @ property def some_property (self, * args, ** kwargs): print "calling some_property getter ({0}, {1}, {2 }) ". format (self, args, kwargs) return self. _ some_property @ some_property.setter def some_property (self, * args, ** kwargs): print "calling some_property setter ({0}, {1}, {2 })". format (self, args, kwargs) self. _ some_property = args [0] @ property def some_other_property (self, * args, ** kwarg S): print "calling some_other_property getter ({0}, {1}, {2 })". format (self, args, kwargs) return self. _ some_other_propertyo = MyClass () # The undecorated method is still a normal behavior mode. The current class instance (self) must be used as the first parameter. O. normal_method #
 
  
> O. normal_method () # normal_method ((
  
   
,), {}) O. normal_method (, x = 3, y = 4) # normal_method ((
   
    
, 1, 2), {'Y': 4, 'x': 3}) # The first parameter of the class method is always the class o. class_method #
    
     
> O. class_method () # class_method ((
     
      
,), {}) O. class_method (, x = 3, y = 4) # class_method ((
      
        , 1, 2), {'Y': 4, 'x': 3}) # In the static method, except for the parameters passed in during the call, there are no other parameters. O. static_method #
       
         O. static_method () # static_method (), {}) o. static_method (1, 2, x = 3, y = 4) # static_method (1, 2), {'Y': 4, 'x': 3 }) # @ property is a way to implement the getter and setter methods. It is wrong to call them directly. # The "read-only" attribute can be implemented by defining only the getter method but not the setter method. O. some_property # Call the getter (
        
          , (), {}) # 'Properties are nice '# "attribute" is a good function o. some_property () # calling some_property getter (
         
           , (), {}) # Traceback (most recent call last): # File"
          
            ", Line 1, in
           
             # TypeError: 'str' object is not callableo. some_other_property # calling some_other_property getter (
            
              , (), {}) # 'Very nice '# o. some_other_property () # calling some_other_property getter (
             
               , (), {}) # Traceback (most recent call last): # File"
              
                ", Line 1, in
               
                 # TypeError: 'str' object is not callableo. some_property = "pythontab" # calling some_property setter (
                
                  , ('Pythontab',), {}) o. some_property # calling some_property getter (
                 
                   , (), {}) # 'Pythontab' o. some_other_property = "pythontab.com" # Traceback (most recent call last): # File"
                  
                    ", Line 1, in
                   
                     # AttributeError: can't set attributeo. some_other_property # calling some_other_property getter (
                    
                      ,(),{})
                    
                   
                  
                 
                
               
              
             
            
           
          
         
        
       
      
     
    
   
  
 
Question 10

Briefly describe the garbage collection mechanism of Python ).

Answer

A lot can be said here. You should mention the following main points:

Python stores reference count for each object in memory ). If the count value is changed to 0, the corresponding object will be allocated in hours, and the memory allocated to the object will be released for use.

Occasionally, reference cycle occurs ). The garbage collector regularly searches for this loop and recycles it. For example, assume that there are two objects, o1 and o2, and the o1.x = o2 and o2.x = o1 conditions are met. If o1 and o2 do not have other code references, they should not continue to exist. However, their reference count is 1.

Python uses some heuristic algorithms (heuristics) to accelerate garbage collection. For example, objects created later are more likely to be recycled. After an object is created, the garbage collector allocates its generation ). Each object is assigned a generation, and the objects assigned to the younger generation are prioritized.

Question 11

Sort the following functions by execution efficiency. They all accept a list of numbers ranging from 0 to 1 as input. This list can be very long. An example of an input list is as follows: [random. random () for I in range (100000)]. How do you prove that your answer is correct.

def f1(lIn):    l1 = sorted(lIn)    l2 = [i for i in l1 if i<0.5]    return [i*i for i in l2]def f2(lIn):    l1 = [i for i in lIn if i<0.5]    l2 = sorted(l1)    return [i*i for i in l2]def f3(lIn):    l1 = [i*i for i in lIn]    l2 = sorted(l1)    return [i for i in l1 if i<(0.5*0.5)]

Answer

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.

import cProfilelIn = [random.random() for i in range(100000)]cProfile.run('f1(lIn)')cProfile.run('f2(lIn)')cProfile.run('f3(lIn)')

In order to provide a complete description, the output results of the above analysis code are as follows:

>>> cProfile.run('f1(lIn)')         4 function calls in 0.045 seconds   Ordered by: standard name   ncalls  tottime  percall  cumtime  percall filename:lineno(function)        1    0.009    0.009    0.044    0.044 
 
  :1(f1)        1    0.001    0.001    0.045    0.045 
  
   :1(
   
    )        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}        1    0.035    0.035    0.035    0.035 {sorted}>>> cProfile.run('f2(lIn)')         4 function calls in 0.024 seconds   Ordered by: standard name   ncalls  tottime  percall  cumtime  percall filename:lineno(function)        1    0.008    0.008    0.023    0.023 
    
     :1(f2)        1    0.001    0.001    0.024    0.024 
     
      :1(
      
       ) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1 0.016 0.016 0.016 0.016 {sorted}>>> cProfile.run('f3(lIn)') 4 function calls in 0.055 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.016 0.016 0.054 0.054 
       
        :1(f3) 1 0.001 0.001 0.055 0.055 
        
         :1(
         
          ) 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 1 0.038 0.038 0.038 0.038 {sorted}
         
        
       
      
     
    
   
  
 

Why is this question raised?

Identifying and avoiding code bottlenecks are very valuable skills. To write a lot of efficient code, you must answer the common sense. in the above example, if the list is small, it is obvious that the sorting is faster first, therefore, if you can filter data before sorting, it is usually a good practice. Other non-obvious problems can still be identified through appropriate tools. Therefore, it is good to understand these tools.

The above is the details of the Python pen exam (latest in 2017). For more information, see other related articles in the first PHP community!

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.