Home  >  Article  >  Backend Development  >  (Comprehensive) Summary of classic examples of python interview questions

(Comprehensive) Summary of classic examples of python interview questions

不言
不言forward
2019-02-23 10:54:045193browse

(Comprehensive) Summary of classic examples of python interview questions

What this article brings to you is a summary of classic examples of (comprehensive) Python interview questions. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you. You helped.

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

1. How to implement singleton mode in Python?

Python has two ways to implement the singleton mode. The following two examples use different ways to implement the singleton mode:

1,

class Singleton(type):
def __init__(cls, name, bases, dict):
super(Singleton, cls).__init__(name, bases, dict)
cls.instance = None
def __call__(cls, *args, **kw):
if cls.instance is None:
cls.instance = super(Singleton, cls).__call__(*args, **kw)
return cls.instance
class MyClass(object):
__metaclass__ = Singleton
print MyClass()
print MyClass()

Use decorator to implement singleton mode

def singleton(cls):
instances = {}
def getinstance():
if cls not in instances:
instances[cls] = cls()
return instances[cls]
return getinstance
@singleton
class MyClass:
…

2: What is a lambda function?

Python allows you to define a small one-line function. The form of defining the lambda function is as follows: labmda parameters: expression The lambda function returns the value of the expression by default. You can also assign it to a variable. The lambda function can accept any number of parameters, including optional parameters, but there is only one expression:

>>> g = lambda x, y: x*y
>>> g(3,4)
12
>>> g = lambda x, y=0, z=0: x+y+z
>>> g(1)
1
>>> g(3, 4, 7)
14

You can also use the lambda function directly without assigning it to a variable:

>>> (lambda x,y=0,z=0:x+y+z)(3,5,6)
14

If your The function is very simple, with only one expression and no commands. You can consider the lambda function. Otherwise, you'd better define a function. After all, functions don't have so many restrictions.

3: How does Python perform type conversion?

Python provides built-in functions to convert variables or values ​​from one type to another. The int function converts a mathematically formatted numeric string into an integer. Otherwise, an error message is returned.

>>> int(”34″)
34
>>> int(”1234ab”) #不能转换成整数
ValueError: invalid literal for int(): 1234ab

The function int can also convert floating point numbers into integers, but the decimal part of the floating point number is truncated.

>>> int(34.1234)
34
>>> int(-2.46)
-2

Function °oat converts integers and strings into floating point numbers:

>>> float(”12″)
12.0
>>> float(”1.111111″)
1.111111

Function str converts numbers into characters:

>>> str(98)
‘98′
>>> str(”76.765″)
‘76.765′

Integer 1 and floating point number 1.0 in python is different. Although their values ​​are equal, they are of different types. The storage format of these two numbers in the computer is also different.

4: How to define a function in Python

The definition form of the function is as follows:

def <name>(arg1, arg2,… argN):
<statements>

The name of the function must also start with a letter and can include underscores " ", but Python keywords cannot be defined as function names. The number of statements within a function is arbitrary, and each statement must be indented by at least one space to indicate that the statement belongs to this function. Where the indentation ends, the function ends naturally.
The following defines a function that adds two numbers:

>>> def add(p1, p2):
print p1, “+”, p2, “=”, p1+p2
>>> add(1, 2)
1 + 2 = 3

The purpose of the function is to hide some complex operations to simplify the structure of the program and make it easier to read. Functions must be defined before they can be called. You can also define a function inside a function, and the internal function can only be executed when the external function is called. When the program calls a function, it goes to the inside of the function to execute the statements inside the function. After the function is executed, it returns to the place where it left the program and executes the next statement of the program.

5: How does Python manage memory?

Python’s memory management is taken care of by the Python interpreter. Developers can be freed from memory management matters and devote themselves to application development, which results in fewer program errors. The program is more robust and the development cycle is shorter

6: How to iterate a sequence in reverse order?

how do I iterate over a sequence in reverse order

If it is a list, the fastest solution is:

list.reverse()
try:
for x in list:
“do something with x”
finally:
list.reverse()

If it is not a list, the most common solution But the slightly slower solution is:

for i in range(len(sequence)-1, -1, -1):
x = sequence[i]
<do something with x>

7: How to convert tuple and list in Python?

The function tuple(seq) can convert all iterable (iterable) sequences into a tuple, with the elements and sorting unchanged.
For example, tuple([1,2,3]) returns (1,2,3), tuple('abc') returns ('a'.'b','c'). If the parameter is already a For tuples, the function directly returns the original object without making any copy, so it is not very expensive to call the tuple() function when you are not sure whether the object is a tuple.
The function list(seq) can convert all sequences and iterable objects into a list, with the elements and sorting unchanged.
For example, list([1,2,3]) returns (1,2,3), list('abc') returns ['a', 'b', 'c']. If the parameter is a list, she will make a copy like set[:]

8: Python interview question: Please write a Python code to delete duplicate elements in a list

You can reorder the list first, and then start scanning from the end of the list. The code is as follows:

if List:
List.sort()
last = List[-1]
for i in range(len(List)-2, -1, -1):
if last==List[i]: del List[i]
else: last=List[i]

9: Python file operation interview questions

How to delete a file using Python?
Use os.remove(filename) or os.unlink(filename);

How to copy a file in Python?
shutil module has a copyfile function that can realize file copy

10: How to generate random numbers in Python?

The standard library random implements a random number generator. The example code is as follows:

import random
random.random()

It will return a random floating point number between 0 and 1

11:如何用Python来发送邮件?

可以使用smtplib标准库。
以下代码可以在支持SMTP监听器的服务器上执行。

import sys, smtplib
fromaddr = raw_input(”From: “)
toaddrs = raw_input(”To: “).split(’,&#39;)
print “Enter message, end with ^D:”
msg = ”
while 1:
line = sys.stdin.readline()
if not line:
break
msg = msg + line
# 发送邮件部分
server = smtplib.SMTP(’localhost’)
server.sendmail(fromaddr, toaddrs, msg)
server.quit()

12:Python里面如何拷贝一个对象?

一般来说可以使用copy.copy()方法或者copy.deepcopy()方法,几乎所有的对象都可以被拷贝
一些对象可以更容易的拷贝,Dictionaries有一个copy方法:

newdict = olddict.copy()

13:有没有一个工具可以帮助查找python的bug和进行静态的代码分析?

有,PyChecker是一个python代码的静态分析工具,它可以帮助查找python代码的bug, 会对代码的复杂度和格式提出警告
Pylint是另外一个工具可以进行coding standard检查。

14:如何在一个function里面设置一个全局的变量?

解决方法是在function的开始插入一个global声明:

def f()
global x

15:用Python匹配HTML tag的时候,eaf5515312973cd1e2c4aca2b4bd67a4和958f55c6e201f79be615af607c97dbf9有什么区别?

当重复匹配一个正则表达式时候, 例如e54b220469ea1f7eeecb6e69f5f72e2b, 当程序执行匹配的时候,会返回最大的匹配值

例如:

import re
s = ‘<html><head><title>Title</title>’
print(re.match(’<.*>’, s).group())

会返回一个匹配而不是

import re
s = ‘<html><head><title>Title</title>’
print(re.match(’<.*?>’, s).group())

则会返回
eaf5515312973cd1e2c4aca2b4bd67a4这种匹配称作贪心匹配 958f55c6e201f79be615af607c97dbf9称作非贪心匹配

16:Python里面search()和match()的区别?

match()函数只检测RE是不是在string的开始位置匹配, search()会扫描整个string查找匹配, 也就是说match()只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话,match()就返回none
例如:

print(re.match(’super’, ’superstition’).span())

会返回(0, 5)

print(re.match(’super’, ‘insuperable’))

则返回None
search()会扫描整个字符串并返回第一个成功的匹配
例如:

print(re.search(’super’, ’superstition’).span())

返回(0, 5)

print(re.search(’super’, ‘insuperable’).span())

返回(2, 7)

17:如何用Python来进行查询和替换一个文本字符串?

可以使用sub()方法来进行查询和替换,sub方法的格式为:sub(replacement, string[, count=0])
replacement是被替换成的文本
string是需要被替换的文本
count是一个可选参数,指最大被替换的数量
例子:

import re
p = re.compile(’(blue|white|red)’)
print(p.sub(’colour’,&#39;blue socks and red shoes’))
print(p.sub(’colour’,&#39;blue socks and red shoes’, count=1))

输出:

colour socks and colour shoes
colour socks and red shoes

subn()方法执行的效果跟sub()一样,不过它会返回一个二维数组,包括替换后的新的字符串和总共替换的数量
例如:

import re
p = re.compile(’(blue|white|red)’)
print(p.subn(’colour’,&#39;blue socks and red shoes’))
print(p.subn(’colour’,&#39;blue socks and red shoes’, count=1))

输出

(’colour socks and colour shoes’, 2)
(’colour socks and red shoes’, 1)

18:介绍一下except的用法和作用?

Python的except用来捕获所有异常, 因为Python里面的每次错误都会抛出 一个异常,所以每个程序的错误都被当作一个运行时错误。
一下是使用except的一个例子:

try:
foo = opne(”file”) #open被错写为opne
except:
sys.exit(”could not open file!”)

因为这个错误是由于open被拼写成opne而造成的,然后被except捕获,所以debug程序的时候很容易不知道出了什么问题
下面这个例子更好点:

try:
foo = opne(”file”) # 这时候except只捕获IOError
except IOError:
sys.exit(”could not open file”)

19:Python中pass语句的作用是什么?

pass语句什么也不做,一般作为占位符或者创建占位程序,pass语句不会执行任何操作,比如:

while False:
pass

pass通常用来创建一个最简单的类:

class MyEmptyClass:
pass

pass在软件设计阶段也经常用来作为TODO,提醒实现相应的实现,比如:

def initlog(*args):
pass #please implement this

20:介绍一下Python下range()函数的用法?

如果需要迭代一个数字序列的话,可以使用range()函数,range()函数可以生成等差级数。
如例:

for i in range(5)
print(i)

这段代码将输出0, 1, 2, 3, 4五个数字
range(10)会产生10个值, 也可以让range()从另外一个数字开始,或者定义一个不同的增量,甚至是负数增量
range(5, 10)从5到9的五个数字
range(0, 10, 3) 增量为三, 包括0,3,6,9四个数字
range(-10, -100, -30) 增量为-30, 包括-10, -40, -70
可以一起使用range()和len()来迭代一个索引序列
例如:

a = [&#39;Nina&#39;, &#39;Jim&#39;, &#39;Rainman&#39;, &#39;Hello&#39;]
for i in range(len(a)):
    print(i, a[i])

21:有两个序列a,b,大小都为n,序列元素的值任意整形数,

无序;要求:通过交换a,b中的元素,使[序列a元素的和]与[序列b元素的和]之间的差最小。
将两序列合并为一个序列,并排序,为序列Source

拿出最大元素Big,次大的元素Small

在余下的序列S[:-2]进行平分,得到序列max,min

将Small加到max序列,将Big加大min序列,重新计算新序列和,和大的为max,小的为min。

Python代码

def mean( sorted_list ):
if not sorted_list:
return (([],[]))
big = sorted_list[-1]
small = sorted_list[-2]
big_list, small_list = mean(sorted_list[:-2])
big_list.append(small)
small_list.append(big)
big_list_sum = sum(big_list)
small_list_sum = sum(small_list)
if big_list_sum > small_list_sum:
return ( (big_list, small_list))
else:
return (( small_list, big_list))
tests = [   [1,2,3,4,5,6,700,800],
[10001,10000,100,90,50,1],
range(1, 11),
[12312, 12311, 232, 210, 30, 29, 3, 2, 1, 1]
]
for l in tests:
l.sort()
print
print “Source List:    ”, l
l1,l2 = mean(l)
print “Result List:    ”, l1, l2
print “Distance:    ”, abs(sum(l1)-sum(l2))
print ‘-*’*40

输出结果

Source List:    [1, 2, 3, 4, 5, 6, 700, 800]
Result List:    [1, 4, 5, 800] [2, 3, 6, 700]
Distance:       99
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Source List:    [1, 50, 90, 100, 10000, 10001]
Result List:    [50, 90, 10000] [1, 100, 10001]
Distance:       38
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Source List:    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Result List:    [2, 3, 6, 7, 10] [1, 4, 5, 8, 9]
Distance:       1
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
Source List:    [1, 1, 2, 3, 29, 30, 210, 232, 12311, 12312]
Result List:    [1, 3, 29, 232, 12311] [1, 2, 30, 210, 12312]
Distance:       21
-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*

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

The above is the detailed content of (Comprehensive) Summary of classic examples of python interview questions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:公众号python爬虫人工智能大数据. If there is any infringement, please contact admin@php.cn delete