Translation 8 required questions in a Python interview

Source: Internet
Author: User
Tags closure for in range

1. What is the output of the following code? Please explain.

defExtendlist (Val, list=[]): List.append (val)returnListlist1= Extendlist (10) List2= Extendlist (123, []) List3= Extendlist ('a')Print "List1 =%s"%List1Print "List2 =%s"%List2Print "list3 =%s"% LIST3

How can you modify the definition of extendlist to produce the following expected behavior?

The result of the above code output would be:

' a '  = [123'a']

Many people mistakenly think of list1=[10],list3=[' a '] because they think the default value of the list parameter will be set to [] each time extendlist is called. But in fact, the new default list is created only once at the moment the function is defined. When Extendlist is called by a list that does not specify a specific parameter, the value of this set of lists is then used. This is because an expression with a default argument is evaluated when the function is defined, not when it is called. So List1 and List3 are manipulated (computed) on the same default list. The List2 is manipulated (computed) on a separate list. (By passing an empty list of its own as the numeric value of the list parameter).

The definition of extendlist can be modified as follows. Despite the creation of a new list, there are no specific list parameters.

The following code may be able to produce the desired result.

def Extendlist (Val, list=None):  if is none:    = []  List.append (val)  return list

With the above modification, the output will become:

List1 = [ten= [123= ['a']

2. What will be the output of this code? Please explain.

def multipliers ():   return [Lambda for in range (4)]     Print  for  in multipliers ()]

How do you modify the definition of the above multipliers to produce the desired result? The result of the above code output is [6, 6, 6, 6] (not what we want [0, 2, 4, 6]).

The problem is due to delayed binding of python closures. This means that when an intrinsic function is called, the value of the parameter is searched within the closure.
Therefore, when any function returned by multipliers () is called, the value of I will be found in a nearby range.
At that time, regardless of whether the returned function was invoked, the for loop was completed and I was given the final value of 3.
Therefore, each returned function is multiplied by the value passed over 3, because the last piece of code passes over the value 2, and they eventually return 6. (3*2)
Incidentally, the Hitchhiker's Guide to Python also points out that there is a widely misunderstood knowledge point in relation to the Lambdas function, but it is not the same as this case. A function created by a lambda expression has no special place, it is actually the same as the function created by def.

Here are some ways to solve this problem. One solution is to use the Python builder.

def multipliers ():    for inch yield Lambda

Another solution is to create a closure that is immediately bound with the default function.

def multipliers ():   return [Lambda for in range (4)]

Another alternative is to use the partial function:

 from Import Partial  from Import Mul def multipliers ():   return  for  in range (4)]

3. What will be the output of this code? Please explain.

class Parent (object):     = 1class  Child1 (parent):    passclass  Child2 (parent):    Pass  Print= 2print= 3print parent.x, child1.x, child2.x

The output will be:

1 1 11 2 13 2 3

What makes a lot of people confused or surprised is why the last line of output is 3 2 3 instead of 3 2 1. Why change the value of child2.x while changing the parent.x? But at the same time not changing the value of child1.x? The key to this answer is that in Python, class variables are internally passed in the form of a dictionary.

If a variable name is not found in the dictionary under the current class.
Search in a more advanced class (such as its parent class) until the referenced variable name is found. (If the reference variable name is not found in its own class and in the higher-level class, a property error will be thrown.) )
Therefore, set X = 1 in the parent class so that the variable x class (with a value of 1) can be referenced in its class and its subclasses. That's why the first printout of the statement is 1 1 1
Therefore, if any of its subclasses are overwritten with a value (say, when we execute the statement child.x = 2), the value is modified only in the subclass. That's why the second printout of the statement is 1 2 1
Finally, if the value is modified in the parent class (for example, when we execute the statement parent.x = 3), the change will affect those values that have not yet been written to the subclass (in this case Child2) that's why the third print statement output is 3 2 3.

4. What is the output of this code under Python2? Please explain.

def div1 (x, y    ): Print " %s/%s =%s " % (x, y, x/y)    def  div2 (y):    print"%s// %s =%s" % (x, y, x//y) div1 (5,2) div1 (5.,2) div2(5,2) Div2 ( 5.,2.)

How will the results be different under the Python3? (assuming, of course, that the above print statements are converted to PYTHON3 syntax)

In Python2, the above code output will be

5/2 = 25.0/2 = 2.55//2 = 25.0//2.0 = 2.0

By default, Python 2 automatically performs shaping calculations if both are integers. Therefore, the 5/2 result is 2, and the 5./2 result is 2.5 Note that in Python2, you can override this behavior by adding the following reference.

From the future import division
Also note that the//operator will always perform shaping division, regardless of the type of operator. This is why even the result of 5.0//2.0 in Python 2 is 2.0.
In Python3, however, there is no such feature, for example, in cases where both ends are shaped, it does not perform the shaping of division
Therefore, in Python3, the following results will be:

5/2 = 2.55.0/2 = 2.55//2 = 25.0//2.0 = 2.0

5. What will the output of the following code be?

list = ['a''b''c' D ' ' e ' ]print list[10:]

The following code outputs [] and does not produce a indexerror error. Try to get the members of a list with an index that exceeds the number of members, as expected.
For example, trying to get list[10] and subsequent members will cause indexerror.
However, attempting to get a slice of the list, starting with an index that exceeds the number of members, does not produce indexerror, but simply returns an empty list.
This is a particularly disgusting problem, because there is no error when running, which makes it difficult to track down bugs.

6. Consider the following code snippet:

1. List = [[]] * 52. List  #  output? 3. List[0].append (4). List  #  output? 5. List[1].append (6). List  #  output? 7. List.append (8). List  #  output?

What results will the 2,4,6,8 output? Try to explain.

The results of the output are as follows:

[ [], [], [], [], []][[], [ten], [ten], [ten], [ten]][[], [ten], [ten], [], [ten], [ten], 20
   
    ]][[10, 20], [10, 20], [10, 20], [10, 20], [10, 20], 30]
   

The explanations are as follows:
The output of the first line is intuitively easy to understand, such as List = [[]] * 5 is simply creating 5 empty lists.
However, the key point of understanding the expression list=[[]] * 5 is that it is not creating a list that contains five separate lists, but rather it is a list that has been created that contains five references to the same list.
Only by understanding this, can we better understand the results of the next output.

List[0].append (10) attaches 10 to the first list.

But since all 5 lists are references to the same list, this result will be:

[10], [10], [10], [10], [10]]

Similarly, list[1].append (20) attaches 20 to the second list. But also because 5 lists are the same list of references, the output is now:

' [[10, 20], [10, 20], [10, 20], [10, 20], [10, 20]]. '

In contrast, List.append (30) appends the entire new element to the list, resulting in:[[10, 20], [10, 20], [10, 20], [10, 20], [10, 20], 30].

7, Given a list of N numbers. Given a list that contains n numbers.

Use a single list build to produce a new list that contains only values that meet the following criteria:
(a) even values
(b) The element is an even slice of the original list.

For example, if LIST[2] contains an even number of values. Then this value should be included in the new list, because the number is in the even sequence of the original list (2 is even). However, if LIST[3] contains an even number,

That number should not be included in the new list because it is in the odd sequence of the original list. A simple workaround for this problem is as follows:

 for inch if x%2 = = 0]

For example, the given list is as follows:

list = [1, 3, 5, 8, 10, 13, 18, 36, 78]

[x for x in list[::2] if x%2 == 0]The result of the list-generation is that

[10, 18, 78]

The step of this expression is to take the number of even slices in the first step and remove all the odd numbers in the second step.

Given the following dictionary subclasses:

class defaultdict (dict):   def __missing__ (self, key):     return []

8. Can the following code be run? Why?

D = defaultdict () d['florp'] = 127

able to run. When key is missing, the Defaultdict class is executed, and the instance of the dictionary automatically instantiates the sequence.

Original link: "8 Essential Python interview Questions"

Translation 8 required questions in a Python 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.