5 excellent answers and Analysis of Python interview questions, and python questions

Source: Internet
Author: User
Tags integer division mul

5 excellent answers and Analysis of Python interview questions, and python questions

The main content of this article is to share with you several T questions in the Python interview, and give the answer and analyze it as follows.

The original article in this article is 5 Great Python Interview Questions. At the same time, thank you @ for pointing out my omissions. I don't have the source mark, but I also like it. I hope you can read the original article at the same time, because each person's understanding is inconsistent, the original content is the most helpful. I have translated many articles for the convenience of finding materials in the future, and as an index, when I look at the original text later, faster. The goal is to see the original article.

Question 1: What is the output of the following code? Give your answer and explain it.

class Parent (object):
 x = 1

class Child1 (Parent):
 pass

class Child2 (Parent):
 pass

print Parent.x, Child1.x, Child2.x
Child1.x = 2
print Parent.x, Child1.x, Child2.x
Parent.x = 3
print Parent.x, Child1.x, Child2.x
answer

The output of the above code is:

1 1 1
1 2 1
3 2 3
What confuses or surprises you is that the output on the last line is 3 2 3 instead of 3 2 1. Why does changing the value of Parent.x also change the value of Child2.x, but at the same time the value of Child1.x does not change?

The key to this answer is that in Python, class variables are handled internally as dictionaries. If the name of a variable is not found in the dictionary of the current class, it will search the ancestor class (such as the parent class) until the referenced variable name is found (if the referenced variable name is neither in its own class nor in the ancestor Found in the class, it will raise an AttributeError exception).

Therefore, setting x = 1 in the parent class makes the value of the class variable X in the reference to the class and any of its subclasses be 1. This is because the output of the first print statement is 1 1 1.

Subsequently, if any of its subclasses rewrite the value (for example, we execute the statement Child1.x = 2), then the value is only changed in the subclass. 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 in any subclass that does not rewrite the value (in this example, the affected child The class is Child2). This is why the third print output is 3 2 3.

Question 2: What will the output of the following code be? Give your answer and explain it?

def div1 (x, y):
 print ("% s /% s =% s"% (x, y, x / y))

def div2 (x, y):
 print ("% s //% s =% s"% (x, y, x // y))

div1 (5,2)
div1 (5., 2)
div2 (5,2)
div2 (5., 2.)
answer

This answer actually depends on whether you are using Python 2 or Python 3.

In Python 3, the expected output is:

5/2 = 2.5
5.0 / 2 = 2.5
5 // 2 = 2
5.0 // 2.0 = 2.0
In Python 2, nonetheless, the output of the above code will be:

5/2 = 2
5.0 / 2 = 2.5
5 // 2 = 2
5.0 // 2.0 = 2.0
By default, if both operands are integers, Python 2 automatically performs integer calculations. As a result, the 5/2 value is 2, while the 5./2 value is `` `2.5``.

Note that despite this, you can overload this behavior in Python 2 (for example to achieve the same result you want in Python 3), by adding the following imports:

from __future__ import division
It should also be noted that the "double dash" (//) operator will always perform division, regardless of the type of operand, which is why 5.0 // 2.0 is 2.0.

Note: In Python 3, the / operator is for floating-point division, and // is for integer division (ie, the quotient has no remainder, such as 10 // 3 and the result is 3, the remainder is truncated, and (-7 ) // The result of 3 is -3. This algorithm is different from many other programming languages. It should be noted that their division operation will take the value of 0. In Python 2, / is the division, which is the same as Python 3. The // operator in the same,)
Question 3: What will the following code output?

list = ['a', 'b', 'c', 'd', 'e']
print list [10:]
answer

The above code will output [] and will not cause an IndexError.

As one would expect, trying to access a member that exceeds the index value of the list will result in IndexError (such as accessing list [10] in the above list). Nonetheless, attempting to access a list of slices starting with an index that exceeds the number of list members will not cause IndexError and will only return an empty list.

A small annoying problem is that it causes bugs, and this problem is difficult to track because it does not cause errors at runtime.

Question 4: What will be the output of the following code? State your answer and explain it?

def multipliers ():
 return [lambda x: i * x for i in range (4)]

print [m (2) for m in multipliers ()]
How would you modify the definition of multipliers to produce the desired result

answer

The output of the above code is [6, 6, 6, 6] (instead of [0, 2, 4, 6]).

The reason for this is late binding caused by Python's late binding of closures, which means that variables in closures are looked up when internal functions are called. So the result is that when any function returned by multipliers () is called, at that time, the value of i is looked up in the surrounding scope at the time it was called. By then, no matter which returned function is called, the for loop It has been completed, the final value of i is 3, so the value of each returned function multiplies is 3. So a value equal to 2 is passed into the above code, they will return a value of 6 (for example: 3 x 2).

(By the way, as pointed out in The Hitchhiker's Guide to Python, there is a common misunderstanding here, something about lambda expressions. The function created by a lambda expression is not special, and created using a common def 'S function exhibits the same performance.)

There are two ways to solve this problem.

The most common solution is to create a closure and bind its parameters immediately by using default parameters. E.g:

def multipliers ():
 return [lambda x, i = i: i * x for i in range (4)]
Another option is that you can use the functools.partial function:

from functools import partial
from operator import mul

def multipliers ():
 return [partial (mul, i) for i in range (4)]
Question 5: What will the output of the following code be? Give your answer and explain it?

def extendList (val, list = []):
 list.append (val)
 return list

list1 = extendList (10)
list2 = extendList (123, [])
list3 = extendList ('a')

print "list1 =% s"% list1
print "list2 =% s"% list2
print "list3 =% s"% list3
How would you modify the definition of extendList to produce the desired result

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 parameter of list will be set to its default value each time extendList is called [].

Nevertheless, what actually happens is that the new default list is only created once when the function is defined. Later, when extendList is not called with the specified list parameter, it uses the same list. This is why when the function is defined, the expression is evaluated with default parameters, not when it is called.

Therefore, list1 and list3 are the same list of operations. And `` '' list2 is an independent list of operations that it creates (by passing its own empty list as the value of the list``` parameter).

The definition of the extendList function can be modified as follows, but 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
Using this improved implementation, the output will be:

list1 = [10]
list2 = [123]
list3 = ['a']
to sum up

Regarding the interview, how can I give the interviewer a good impression? For example, if people test you what is the output of this program, you can not only answer it, but if you can point out that this code can be optimized under the condition that the function is unchanged, the examiner will definitely shine. Right. In any case, a solid basic knowledge is required.

The above is the whole content of the answer and analysis of the 5 good Python interview questions in this article, I hope to help everyone. Interested friends can continue to refer to other related topics on this site, if there are deficiencies, please leave a message to indicate. Thank you friends for your support!

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.