Home >Backend Development >Python Tutorial >Detailed summary of python interview questions (with answers)
This article brings you a summary of python interview questions (with answers). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.
##1. What is the output of the following code? please explain.Recommended related articles: "Summary of python interview questions in 2020 (latest)"
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" % list3How to modify the definition of extendList to produce the following expected behavior?The output result of the above code will be:
list1 = [10, 'a'] list2 = [123] list3 = [10, 'a']Many people will mistakenly think that list1=[10], list3=['a'], because they thought that every time extendList is called, the default value of the list parameter will be set to []. But the actual situation is that the new default list is only used at the moment the function is defined. Created once. When extendList is called without specifying a specific parameter list, the values of this set of list will be used subsequently. This is because expressions with default parameters are evaluated when the function is defined, not when it is called. Therefore list1 and list3 operate (calculate) on the same default list. And list2 operates (calculates) on a separate list. (By passing an own empty list as the value of the list argument). The definition of extendList can be modified as follows. Although, creates a new list with no specific list parameters. The following code may produce the desired results.
def extendList(val, list=None): if list is None: list = [] list.append(val) return listWith the above modification, the output result will become:
list1 = [10] list2 = [123] list3 = ['a']2. What will be the output result of the following code? please explain.
def multipliers(): return [lambda x : i * x for i in range(4)] print [m(2) for m in multipliers()]How do you modify the definition of multipliers above to produce the desired results? The result output by the above code is [6, 6, 6, 6] (not [0, 2, 4, 6] as we thought). The above problem is caused by the delayed binding of Python closures. This means that when the inner function is called, the value of the argument is looked up within the closure. Therefore, when any function returned by multipliers() is called, the value of i will be looked up in the nearby range. At that point, regardless of whether the returned function has been called, the for loop has completed and i is assigned the final value of 3. Therefore, the function returned each time is multiplied by the passed value 3, because the value passed in the previous code is 2, and they eventually return 6 (3*2). Coincidentally, "The Hitchhiker’s Guide to Python" also pointed out that there is also a widely misunderstood knowledge point related to lambdas functions, but it is different from this case. There is nothing special about the function created by lambda expression. It is actually the same as the function created by def. Here are some ways to solve this problem. One solution is to use Python generators.
def multipliers(): for i in range(4): yield lambda x : i * xAnother solution is to create a closure and bind it immediately using the default function.
def multipliers(): return [lambda x, i=i : i * x for i in range(4)]An alternative is to use a partial function:
from functools import partial from operator import mul def multipliers(): return [partial(mul, i) for i in range(4)]3. What will be the output of the following code? please explain.
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.xThe output result will be:
1 1 1 1 2 1 3 2 3What confuses or surprises many people is why the last line of output is 3 2 3 instead of 3 2 1. Why is it also changing parent.x at the same time? Changed the value of child2.x? But at the same time the value of Child1.x is not changed? The key to this answer is that in Python, class variables are passed internally as a dictionary. If a variable name is not found in the dictionary under the current class. Then search exhaustively in higher-level classes (such as its parent class) until the referenced variable name is found. (If the reference variable name is not found in its own class or a higher-level class, an attribute error will be raised.) Therefore, set x = 1 in the parent class and let the variable x class (with value 1) Can be referenced in its class and its subclasses. This is why the output of the first print statement is 1 1 1 Therefore, if any of its subclasses are overwritten with a value (for example, when we execute the statement Child1.x = 2), this value Modified only in subclasses. This is why the output of the second print statement is 1 2 1Finally, if this value is modified in the parent class, (for example, when we execute the statement Parent.x = 3), this change Will affect those values that have not been overridden by the subclass (in this example, Child2). This is why the output result of the third print statement is 3 2 34. The following code outputs the result under Python2 What will it be? please explain.
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.)How will the results be different under Python3? (Assuming, of course, that the above print statement is converted to Python3's syntax) In Python2, the output of the above code will be
5/2 = 2 5.0/2 = 2.5 5//2 = 2 5.0//2.0 = 2.0By default, Python 2 automatically performs integer calculations if both is an integer. Therefore, 5/2 results in 2, and 5./2 results in 2.5Note that in Python 2, you can override this behavior by adding the following reference. from future import division
例如,在两端都是整形的情况下,它不会执行整形除法
因此,在Python3中,将会是如下结果:
5/2 = 2.5 5.0/2 = 2.5 5//2 = 2 5.0//2.0 = 2.0
注: 在 Python 3 中,/ 操作符是做浮点除法,而 // 是做整除(即商没有余数,比如 10 // 3 其结果就为 3,余数会被截除掉,而 (-7) // 3 的结果却是 -3。这个算法与其它很多编程语言不一样,需要注意,它们的整除运算会向0的方向取值。而在 Python 2 中,/ 就是整除,即和 Python 3 中的 // 操作符一样)
5、下面代码的输出结果将是什么?
list = ['a', 'b', 'c', 'd', 'e'] print list[10:]
下面的代码将输出[],不会产生IndexError错误。就像所期望的那样,尝试用超出成员的个数的index来获取某个列表的成员。
例如,尝试获取list[10]和之后的成员,会导致IndexError.
然而,尝试获取列表的切片,开始的index超过了成员个数不会产生IndexError,而是仅仅返回一个空列表。
这成为特别让人恶心的疑难杂症,因为运行的时候没有错误产生,导致bug很难被追踪到。
6、考虑下列代码片段:
list = [ [ ] ] * 5 list # output? list[0].append(10) list # output? list[1].append(20) list # output? list.append(30) list # output?
2,4,6,8行将输出什么结果?试解释。
输出的结果如下:
[[], [], [], [], []] [[10], [10], [10], [10], [10]] [[10, 20], [10, 20], [10, 20], [10, 20], [10, 20]] [[10, 20], [10, 20], [10, 20], [10, 20], [10, 20], 30]
解释如下:
第一行的输出结果直觉上很容易理解,例如 list = [ [ ] ] * 5 就是简单的创造了5个空列表。然而,理解表达式list=[ [ ] ] * 5的关键一点是它不是创造一个包含五个独立列表的列表,而是它是一个创建了包含对同一个列表五次引用的列表。只有了解了这一点,我们才能更好的理解接下来的输出结果。
list[0].append(10) 将10附加在第一个列表上。
但由于所有5个列表是引用的同一个列表,所以这个结果将是:
[[10], [10], [10], [10], [10]]
同理,list[1].append(20)将20附加在第二个列表上。但同样由于5个列表是引用的同一个列表,所以输出结果现在是:
[[10, 20], [10, 20], [10, 20], [10, 20], [10, 20]]
作为对比, list.append(30)是将整个新的元素附加在外列表上,因此产生的结果是: [[10, 20], [10, 20], [10, 20], [10, 20], [10, 20], 30].
7、Given a list of N numbers。
给定一个含有N个数字的列表。
使用单一的列表生成式来产生一个新的列表,该列表只包含满足以下条件的值:
(a)偶数值
(b)元素为原始列表中偶数切片。
例如,如果list[2]包含的值是偶数。那么这个值应该被包含在新的列表当中。因为这个数字同时在原始列表的偶数序列(2为偶数)上。然而,如果list[3]包含一个偶数,
那个数字不应该被包含在新的列表当中,因为它在原始列表的奇数序列上。
对此问题的简单解决方法如下:
[x for x in list[::2] if x%2 == 0]
例如,给定列表如下:
list = [ 1 , 3 , 5 , 8 , 10 , 13 , 18 , 36 , 78 ]
列表生成式[x for x in list[::2] if x%2 == 0] 的结果是,
[10, 18, 78]
这个表达式工作的步骤是,第一步取出偶数切片的数字,
第二步剔除其中所有奇数。
8、给定以下字典的子类,下面的代码能够运行么?为什么?
class DefaultDict(dict): def __missing__(self, key): return []d = DefaultDict() d['florp'] = 127
能够运行。
当key缺失时,执行DefaultDict类,字典的实例将自动实例化这个数列。
相关学习推荐:python视频教程
The above is the detailed content of Detailed summary of python interview questions (with answers). For more information, please follow other related articles on the PHP Chinese website!