Home  >  Article  >  Backend Development  >  Code questions that must be tested in python interviews

Code questions that must be tested in python interviews

不言
不言forward
2019-02-23 10:25:204619browse

Code questions that must be tested in python interviews

The content of this article is about the code questions that must be tested in python interviews. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. helped.

Recommended related articles: "2020 python interview questions summary (latest)"

Question 1: What will be the output of the following code? Give your answer and 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.x

The answer is

1 1 1
1 2 1
3 2 3

What may confuse or surprise you is that the output of 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 treated internally as dictionaries. If the name of a variable is not found in the dictionary of the current class, the ancestor class (such as the parent class) will be searched until the referenced variable name is found (if the referenced variable name is neither in its own class nor in the ancestor class) class, an AttributeError exception will be raised).

Thus, setting x = 1 in a parent class causes the class variable X to have a value of 1 in references to that class and any of its subclasses. This is because the output of the first print statement is 1 1 1.

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

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

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

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

p1(5,2)
p1(5.,2)
p2(5,2)
p2(5.,2.)
5/2 = 2
5.0/2.0=2.5
5/2=2
5/2=2

Answer

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

In Python 3, the desired output is:

5/2 = 2.5
5.0/2 = 2.5
5//2 = 2
5.0//2.0 = 2.0

In Python 2, however, 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

Default, if two The operands are all integers, and Python 2 automatically performs integer calculations. As a result, 5/2 has a value of 2, whereas 5./2 has a value of "2.5``.

Note that, however, you can override this behavior in Python 2 (e.g. to achieve what you want in Python 3), by adding the following import:

from__future__ import pision
Also note that the "double dash" (//) operator will always perform an integer division, regardless of the operands type, which is why 5.0//2.0 has a value of 2.0.

Note: In Python 3, the / operator does floating point division, and // does integer division (that is, the quotient has no remainder, such as 10 / / 3 The result is 3, the remainder will be truncated, and (-7) // The result of 3 is -3. This algorithm is different from many other programming languages. It should be noted that their integer division operations will move towards 0 The direction of the value. In Python 2, / is an integer division, which is the same as the // operator in Python 3,)

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 value that exceeds the list index members will cause an IndexError (e.g. accessing list[10] of the above list). However, attempting to access a slice of a list starting at an index that exceeds the number of members in the list will not cause an IndexError, and will simply return an empty list.

A nasty little problem is that it causes bugs, and the problem is difficult to track down because it does not raise an error at runtime.

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

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 results

Answer

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

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

(顺便说下,正如在 The Hitchhiker’s Guide to Python 中指出的,这里有一点普遍的误解,是关于 lambda 表达式的一些东西。一个 lambda 表达式创建的函数不是特殊的,和使用一个普通的 def 创建的函数展示的表现是一样的。)

这里有两种方法解决这个问题

最普遍的解决方案是创建一个闭包,通过使用默认参数立即绑定它的参数。例如:

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

另外一个选择是,你可以使用 functools.partial 函数

from functools import partial
from operator import mul

def multipliers():
    return [partial(mul, i) for i in range(4)]

问题五:以下的代码的输出将是什么? 说出你的答案并解释?

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

你将如何修改 extendList 的定义来产生期望的结果

以上代码的输出为:

list1 = [10, 'a']
list2 = [123]
list3 = [10, 'a']

许多人会错误的认为 list1 应该等于 [10] 以及 list3 应该等于 [‘a’]。认为 list 的参数会在 extendList 每次被调用的时候会被设置成它的默认值 [ ]。

尽管如此,实际发生的事情是,新的默认列表仅仅只在函数被定义时创建一次。随后当 extendList 没有被指定的列表参数调用的时候,其使用的是同一个列表。这就是为什么当函数被定义的时候,表达式是用默认参数被计算,而不是它被调用的时候。

因此,list1 和 list3 是操作的相同的列表。而 "`list2是操作的它创建的独立的列表(通过传递它自己的空列表作为list"参数的值)。

extendList 函数的定义可以做如下修改,但,当没有新的 list 参数被指定的时候,会总是开始一个新列表,这更加可能是一直期望的行为。

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

使用这个改进的实现,输出将是:

list1 = [10]
list2 = [123]
list3 = ['a']

相关学习推荐:python视频教程

The above is the detailed content of Code questions that must be tested in python interviews. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete