search
HomeBackend DevelopmentPython TutorialCode questions that must be tested in python interviews

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. If there is any infringement, please contact admin@php.cn delete
Python vs. C  : Understanding the Key DifferencesPython vs. C : Understanding the Key DifferencesApr 21, 2025 am 12:18 AM

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Python vs. C  : Which Language to Choose for Your Project?Python vs. C : Which Language to Choose for Your Project?Apr 21, 2025 am 12:17 AM

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

Reaching Your Python Goals: The Power of 2 Hours DailyReaching Your Python Goals: The Power of 2 Hours DailyApr 20, 2025 am 12:21 AM

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Maximizing 2 Hours: Effective Python Learning StrategiesMaximizing 2 Hours: Effective Python Learning StrategiesApr 20, 2025 am 12:20 AM

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Choosing Between Python and C  : The Right Language for YouChoosing Between Python and C : The Right Language for YouApr 20, 2025 am 12:20 AM

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python vs. C  : A Comparative Analysis of Programming LanguagesPython vs. C : A Comparative Analysis of Programming LanguagesApr 20, 2025 am 12:14 AM

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

2 Hours a Day: The Potential of Python Learning2 Hours a Day: The Potential of Python LearningApr 20, 2025 am 12:14 AM

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python vs. C  : Learning Curves and Ease of UsePython vs. C : Learning Curves and Ease of UseApr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment