python面试题汇总(史上最全)

python面试题汇总(史上最全)python 面试题对于机器学习算法工程师而言 Python 是不可或缺的语言 它的优美与简洁令人无法自拔 那么你了解过 Python 编程面试题吗 今天我们就来了解一下 1 python 下多线程的限制以及多进程中传递参数的方式 1 python 多线程有个全局解释器锁 globalinterp 这个锁的意思是任一时间只能有一个线程使用解释器 跟单 cpu 跑多个程序一个意思 大家都是轮着用的 这叫 并发 不是 并行 多进程间共享数据 可以使用 multiprocess

python面试题

对于机器学习算法工程师而言,Python是不可或缺的语言,它的优美与简洁令人无法自拔。那么你了解过Python编程面试题吗?今天我们就来了解一下! 1、python 下多线程的限制以及多进程中传递参数的方式 
 在UNIX平台上,当某个进程终结之后,该进程需要被其父进程调用wait,否则进程成为僵尸进程(Zombie)。所以,有必要对每个Process对象调用join()方法 (实际上等同于wait) 。对于多线程来说,由于只有一个进程,所以不存在此必要性。 多进程应该避免共享资源。在多线程中,我们可以比较容易地共享资源,比如使用全局变量或者传递参数。在多进程情况下,由于每个进程有自己独立的内存空间,以上方法并不合适。此时我们可以通过共享内存和Manager的方法来共享资源。 但这样做提高了程序的复杂度,并因为同步的需要而降低了程序的效率。 5、Python 里面如何拷贝一个对象? 标准库中的copy模块提供了两个方法来实现拷贝。一个方法是copy,它返回和参数包含内容一样的对象。使用deepcopy方法,对象中的属性也被复制。 
 用以上解释器进行编译外,技术高超的开发者还可以按照自己的需求自行编写Python解释器来执行 Python代码,十分的方便! 9、列举布尔值为 False的常见值? 0, [] , () , {} , '' , False , None 10、字符串、列表、元组、字典每个常用的 5个方法? 字符串:repleace,strip,split,reverse,upper,lower,join..... 列表:append,pop,,remove,sort,count,index..... 元组:index,count,__len__(),__dir__() 字典:get,keys,values,pop,popitems,clear,,items..... 11、lambda表达式格式以及应用场景? 表达式格式:lambda后面跟一个或多个参数,紧跟一个冒号,以后是一个表达式。冒号前是参数,冒号后是返回值。例如:lambda x : 2x 应用场景:经 常与一些内置函数 相结合使用, 比如说 

14、is和==的区别?

 is:判断内存地址是否相等; ==:判断数值是否相等。 
原理:将系统中的所有内存块根据其存活时间划分为不同的集合,每一个集合就成 为一个“代”, 垃圾收集的频率随着“代”的存活时间的增大而减小。也就是说,活得越长的对象,就越不可能是垃圾, 就应该减少对它的垃圾收集频率。那么如何来衡量这个存活时间:通常是利用几次垃圾收集动作来衡量, 如果一个对象经过的垃圾收集次数越多,可以得出:该对象存活时间就越长。 17、python的可变类型和不可变类型? 不可变类型(数字、字符串、元组、不可变集合); 可变类型(列表、字典、可变集合)。 18、Python里面search()和match()的区别? match()函数只检测RE是不是在string的开始位置匹配,search()会扫描整个 string查找匹配, 也就是说match() 只有在0位置匹配成功的话才有返回,如果不是开始位置匹配成功的话, match()就返回none 

19、用Python匹配HTML tag的时候,<.>和<.?>有什么区别?
前者是贪婪匹配,会从头到尾匹配 xyz,而后者是非贪婪匹配,只匹配到第一个 >。
20、Python里面如何生成随机数? import random;
random.random();






2021年最新Python面试题及答案

请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述
请添加图片描述


















Python基础知识笔试

一、单选题(2.5分*20题)

  1.  下列哪个表达式在Python中是非法的? B 

附录:Python常见面试题精选

 (2) __new__返回生成的实例,可以返回父类(通过super(当前类名, cls)的方式)__new__出来的实例, 
 【参考答案】 
 【参考答案】 
 【参考答案】 
s = "hfkfdlsahfgdiuanvzx" s = list(set(s)) s.sort(reverse=False) print("".join(s)) 
print(len(set(s)) == len(set(t)) == len(set(zip(s, t)))) 

【参考答案】

 ip2int = lambda x:sum([256**j*int(i) for j,i in enumerate(x.split('.')[::-1])]) 
 def romanToInt(s): table = { 
   'M':1000, 'CM':900, 'D':500, 'CD':400, 'C':100, 'XC':90, 'L':50, 'XL': 40, 'X':10, 'IX':9, 'V':5, 'VI':4, 'I':1} result = 0 for i in range(len(s)): if i > 0 and table[s[i]] > table[s[i-1]]: result += table[s[i]] result -= 2 * table[s[i-1]] else: result += table[s[i]] return result 
 def isParenthesesValid(s): pars = [None] parmap = { 
   ')': '(', '}': '{', ']': '['} for c in s: if c in parmap: if parmap[c] != pars.pop(): return False else: pars.append(c) return len(pars) == 1 
 1211  
 def CountAndSay(n): ans = "1" n -= 1 while n > 0: res = "" pre = ans[0] count = 1 for i in range(1, len(ans)): if pre == ans[i]: count += 1 else: res += str(count) + pre pre = ans[i] count = 1 res += str(count) + pre ans = res n -= 1 return ans 

题14:不使用sqrt

 函数,试编写squareRoot()函数,输入一个正数,输出它的平方根的整 
 def squareRoot(x): result = 1.0 while abs(result * result - x) > 0.1: result = (result + x / result) / 2 return int(result) 
 import re 
 import re str = ' 
   
中国
'
res = re.findall(r'
(.*?)
'
,str) print(res)
 结果如下: 【参考答案】 
import re match = re.compile('www\....?').match("www.baidu.com") if match: print(match.group()) else: print("NO MATCH") 
 import re example = " 
   
test1
test2
"
Result = re.compile("
.*"
).search(example) print("Result = %s" % Result.group())
test1
test2

 四、 列表、字典、元组、数组、矩阵(9题) 
 [1, 2, 3, 4, 5, 6]。 【参考答案】 a = [[1, 2], [3, 4], [5, 6]] print([j for i in a for j in i]) 
def testFun(): temp = [lambda x : i*x for i in range(5)] return temp for everyLambda in testFun(): print (everyLambda(3)) 

结果如下: 【参考答案】

 12 12 12 12 12 
 * * * * * 

参考代码如下: 【参考答案】

 n = 5 for i in range(1,n+1): print(' '*(n-(i-1))+'*'*(2*i-1)) 
 函数FindPivot(li),输入数组,输出其中的支配点和支配数,若数组中不存在支配数,输出None。 

例如:[3,3,1,2,2,1,2,2,4,2,2,1,2,3,2,2,2,2,2,4,1,3,3]中共有23个元素,其中元素2出现了12次,其支配点和支配数组合是(18, 2)。 【参考答案】

 def FindPivot(li): mid = len(li)/2 for l in li: count = 0 i = 0 mark = 0 while True: if l == li[i]: count += 1 temp = i i += 1 if count > mid: mark = temp return (mark, li[mark]) if i > len(li) - 1: break 
 def S1(L_in): l1 = sorted(L_in) l2 = [i for i in l1 if i<0.5] return [i*i for i in l2] def S2(L_in): l1 = [i for i in L_in if i<0.5] l2 = sorted(l1) return [i*i for i in l2] def S3(L_in): l1 = [i*i for i in L_in] l2 = sorted(l1) return [i for i in l2 if i<(0.5*0.5)] 
import random import cProfile L_in = [random.random() for i in range()] cProfile.run('S1(L_in)') cProfile.run('S2(L_in)') cProfile.run('S3(L_in)') 
 函数spiralOrder(matrix),以螺旋顺序返回矩阵的所有元素。 
 def spiralOrder(matrix): if len(matrix) == 0 or len(matrix[0]) == 0: return [] ans = [] left, up, down, right = 0, 0, len(matrix) - 1, len(matrix[0]) - 1 while left <= right and up <= down: for i in range(left, right + 1): ans += matrix[up][i], up += 1 for i in range(up, down + 1): ans += matrix[i][right], right -= 1 for i in reversed(range(left, right + 1)): ans += matrix[down][i], down -= 1 for i in reversed(range(up, down + 1)): ans += matrix[i][left], left += 1 return ans[:(len(matrix) * len(matrix[0]))] 
 对于一个给定的二维数组表示的矩阵,以及两个正整数r和c,分别表示所需重新整形矩阵的行数和列数。reshape函数生成一个新的矩阵,并且将原矩阵的所有元素以与原矩阵相同的行遍历顺序填充进去,将该矩阵重新整形为一个不同大小的矩阵但保留其原始数据。对于给定矩阵和参数的reshape操作是可以完成且合法的,则输出新的矩阵;否则,输出原始矩阵。请使用Python语言实现reshape函数。 例如: 输入 

r, c 输出

说明

def matrixReshape(nums, r, c): """ if r * c != len(nums) * len(nums[0]): return nums m = len(nums) n = len(nums[0]) ans = [[0] * c for _ in range(r)] for i in range(r * c): ans[i / c][i % c] = nums[i / n][i % n] return ans 
 【参考答案】 
 import heapq def kthSmallest(matrix, k): visited = { 
   (0, 0)} heap = [(matrix[0][0], (0, 0))] while heap: val, (i, j) = heapq.heappop(heap) k -= 1 if k == 0: return val if i + 1 < len(matrix) and (i + 1, j) not in visited: heapq.heappush(heap, (matrix[i + 1][j], (i + 1, j))) visited.add((i + 1, j)) if j + 1 < len(matrix) and (i, j + 1) not in visited: heapq.heappush(heap, (matrix[i][j + 1], (i, j + 1))) visited.add((i, j + 1)) 
def largestRectangleArea(heights): stack=[] i=0 area=0 while i<len(heights): if stack==[] or heights[i]>heights[stack[len(stack)-1]]: # 递增直接入栈 stack.append(i) else: # 不递增开始弹栈 curr=stack.pop() if stack == []: width = i else: width = i-stack[len(stack)-1]-1 area=max(area,width*heights[curr]) i-=1 i+=1 while stack != []: curr = stack.pop() if stack == []: width = i else: width = len(heights)-stack[len(stack)-1]-1 area = max(area,width*heights[curr]) return area 

五、 设计模式(3

 题) 

【参考答案】

class Singleton(object): def __new__(cls, *args, **kw): if not hasattr(cls, '_instance'): orig = super(Singleton, cls) cls._instance = orig.__new__(cls, *args, **kw) return cls._instance 
class Person: def __init__(self): self.name = None self.gender = None def getName(self): return self.name def getGender(self): return self.gender class Male(Person): def __init__(self, name): print("Hello Mr." + name) class Female(Person): def __init__(self, name): print("Hello Miss." + name) class Factory: def getPerson(self, name, gender): if(gender == 'M'): return Male(name) if(gender == 'F'): return Female(name) if __name__ == '__main__': factory = Factory() person = factory.getPerson("Huang", "M") 
import itertools class Publisher: def __init__(self): self.observers = set() def add(self, observer, *observers): for observer in itertools.chain((observer, ), observers): self.observers.add(observer) observer.update(self) def remove(self, observer): try: self.observers.discard(observer) except ValueError: print('移除 {} 失败!'.format(observer)) def notify(self): [observer.update(self) for observer in self.observers] class DefaultFormatter(Publisher): def __init__(self, name): Publisher.__init__(self) self.name = name self._data = 0 def __str__(self): return "{}: '{}' 的值 = {}".format(type(self).__name__, self.name, self._data) @property def data(self): return self._data @data.setter def data(self, new_value): try: self._data = int(new_value) except ValueError as e: print('错误: {}'.format(e)) else: self.notify() class HexFormatter: def update(self, publisher): print("{}: '{}' 的十六进制值 = {}".format(type(self).__name__, publisher.name, hex(publisher.data))) class BinaryFormatter: def update(self, publisher): print("{}: '{}' 的二进制值 = {}".format(type(self).__name__, publisher.name, bin(publisher.data))) def main(): df = DefaultFormatter('test1') print(df) hf = HexFormatter() df.add(hf) df.data = 37 print(df) bf = BinaryFormatter() df.add(bf) df.data = 23 print(df) df.remove(hf) df.data = 56 print(df) df.remove(hf) df.add(bf) df.data = 'hello' print(df) df.data = 7.2 print(df) if __name__ == '__main__': main() 
def preorder(root, res=[]): if not root: return res.append(root.val) preorder(root.left,res) preorder(root.right,res) return res 

【参考答案】

def binary_search(num_list, x): num_list = sorted(num_list) left, right = 0, len(num_list) - 1 while left <= right: mid = (left + right) // 2 if num_list[mid] > x: right = mid - 1 elif num_list[mid] < x: left = mid + 1 else:  return '待查元素{ 
   0}在排序后列表中的下标为: { 
   1}'.format(x, mid) return '待查找元素%s不存在指定列表中' %x 题 
 33:编写Python函数maxDepth(),实现获取二叉树root最大深度。 

难度:★★★★☆ 【参考答案】

def maxDepth(self, root): if root == None: return 0 return max(self.maxDepth(root.left),self.maxDepth(root.right))+1 
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def istree(pRoot1, pRoot2): if not pRoot2: return True if not pRoot1 and pRoot2: return False if pRoot1.val != pRoot2.val: return False elif pRoot1.val == pRoot2.val: return istree(pRoot1.left, pRoot2.left) and istree(pRoot1.right, pRoot2.right) def HasSubtree(pRoot1, pRoot2): if not pRoot1 or not pRoot2: return False if pRoot1.val == pRoot2.val: return istree(pRoot1, pRoot2) else: return HasSubtree(pRoot1.left, pRoot2) or HasSubtree(pRoot1.right, pRoot2) 
def VerifySquenceOfBST(sequence): if not sequence: return False i= 0 for i in range(len(sequence)-1): if sequence[i]>sequence[-1]: break if i < len(sequence)-2: for j in range(i+1,len(sequence)-1): if sequence[j]<sequence[-1]: return False left = True right = True if i>0: left = VerifySquenceOfBST(sequence[:i]) elif i< len(sequence)-2: right = VerifySquenceOfBST(sequence[i:-1]) return left and right 
import os os.chdir('D:\\') with open('test.txt') as test: count = 0 for i in test.read(): if i.isupper(): count+=1 print(count) 
 def print_directory_contents(sPath): import os for sChild in os.listdir(sPath): sChildPath = os.path.join(sPath,sChild) if os.path.isdir(sChildPath): print_directory_contents(sChildPath) else: print(sChildPath) 

【参考答案】

 class FileNode(object): def __init__(self, name): self.isFolder = True self.childs = { 
   } self.name = name self.data = "" class FileSystem(object): def __init__(self): self.root = FileNode("/") def ls(self, path): fd = self.lookup(path, False) if not fd: return [] if not fd.isFolder: return [fd.name] files = [] for file in fd.childs: files.append(file) files.sort() return files def lookup(self, path, isAutoCreate): path = path.split("/") p = self.root for name in path: if not name: continue if name not in p.childs: if isAutoCreate: p.childs[name] = FileNode(name) else: return None p = p.childs[name] return p def mkdir(self, path): self.lookup(path, True) # 测试 obj = FileSystem() obj.mkdir("/test/path") obj.ls("/test") 
 八、 网络编程(4题) 

【参考答案】

 import socket import threading,getopt,sys,string opts, args = getopt.getopt(sys.argv[1:], "hp:l:",["help","port=","list="]) list=50 port=8001 for op, value in opts: if op in ("-x","--maxconn"): list = int(value) elif op in ("-p","--port"): port = int(value) def Config(client, address): try: client.settimeout(500) buf = client.recv(2048) client.send(buf) except socket.timeout: print('time out') client.close() def main(): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind(('localhost', port)) sock.listen(list) while True: client,address = sock.accept() thread = threading.Thread(target=Config, args=(client, address)) thread.start() if __name__ == '__main__': main() 

难度:★★☆☆☆

select a.s_id, b.s_name, avg(a.s_score) as avg_score from Score a, Student b where a.s_id=b.s_id group by a.s_id, b.s_name having avg(a.s_score)>80 
select b.s_id, b.s_name from Score a, Student b where a.s_id=b.s_id group by b.s_id, b.s_name having count(a.c_id)<(select count(c_id) from Course) 

题46:按照44题所给条件,编写SQL语句查询所有课程第2

 名和第3名的学生信息及该课 
 select * from ( select a.s_id, b.s_name, b.s_birth, b.s_sex, a.c_id, a.s_score, row_number() over (partition by a.c_id order by a.s_score desc) rno from Score a, Student b where a.s_id=b.s_id ) as a where a.rno in (2, 3) order by c_id, rno 
 【参考答案(使用SQLServer)】 
 select a.s_id, d.s_name, a.s_score, a.c_id, b.c_name, b.t_id, c.t_name from Score a, Course b, Teacher c, Student d where a.c_id=b.c_id and b.t_id=c.t_id and a.s_id=d.s_id and a.s_score<60 and c.t_id in ( SELECT c.t_id FROM Score a, Course b, Teacher c where a.c_id=b.c_id and b.t_id=c.t_id and a.s_score<60 group by c.t_id having count(1)>1 ) 
 难度:★★★★☆ 

【参考答案(使用SQLServer)】

select a.c_id, b.c_name, a.s_score, COUNT(1) 人数, (select COUNT(1) from Score c where c.c_id=a.c_id and c.s_score>=a.s_score) 累计人数 from Score a, Course b where a.c_id=b.c_id group by a.c_id, b.c_name, a.s_score order by a.c_id, b.c_name, a.s_score desc; 

十、 图形图像与可视化(2题)

 【参考答案】 

以?(?)=6?2+7?+13为例,代码如下:

 def Quadratic_Function(x): return 6*x**2 + 7*x + 13 import numpy as np import matplotlib.pyplot as plt from ipywidgets import interact def plot_ladder(laddernum): x = np.linspace(-5, 5, num=100) y = Quadratic_Function(x) plt.plot(x, y) a = np.linspace(-5, 5, num=laddernum) for i in range(laddernum): plt.plot([a[i], a[i]], [0, Quadratic_Function(a[i])], color="blue") ladders = [] for i in range(laddernum): ladders.append([a[i], Quadratic_Function(a[i])]) npladders = np.array(ladders) plt.plot(npladders[:,0], npladders[:,1]) interact(plot_ladder, laddernum=(1, 80, 1)) 

在这里插入图片描述

请据此使用Python语言绘制适当的图形并分析得到结论。 【参考答案】

import matplotlib.pyplot as plt plt.figure(figsize=(10, 5)) # 年龄 age = [34, 40, 37, 30, 44, 36, 32, 26, 32, 36] # 收入 income = [7000, 9000, 3380, 3780, 3660, 1600, 3320, 2400, 1500, 2800] # 消费额 expense = [1230, 1140, 1350, 1390, 1170, 1210, 1330, 1400, 1330, 1330] # 年龄,收入 散点图 ax1 = plt.subplot(121) ax1.scatter(age, income) ax1.set_title('年龄,收入 散点图', family='kaiti', size=16) # 年龄,消费额 散点图 ax2 = plt.subplot(122) ax2.scatter(age, expense) ax2.set_title('年龄,消费额 散点图', family='kaiti', size=16) plt.show() 

在这里插入图片描述

从图中可以看到,顾客年龄与消费额几近负相关,收入与消费额也几乎负相关,而年龄与收入之间没有特别明显的关联关系。

140.对Flask蓝图(Blueprint)的理解?
蓝图的定义
蓝图 /Blueprint 是Flask应用程序组件化的方法,可以在一个应用内或跨越多个项目共用蓝图。使用蓝图可以极大简化大型应用的开发难度,也为Flask扩展提供了一种在应用中注册服务的集中式机制。 蓝图的应用场景:
把一个应用分解为一个蓝图的集合。这对大型应用是理想的。一个项目可以实例化一个应用对象,初始化几个扩展,并注册一集合的蓝图。
以URL前缀和/或子域名,在应用上注册一个蓝图。URL前缀/子域名中的参数即成为这个蓝图下的所有视图函数的共同的视图参数(默认情况下) 在一个应用中用不同的URL规则多次注册一个蓝图。
通过蓝图提供模板过滤器、静态文件、模板和其他功能。一个蓝图不一定要实现应用或视图函数。
初始化一个Flask扩展时,在这些情况中注册一个蓝图。 蓝图的缺点:
不能在应用创建后撤销注册一个蓝图而不销毁整个应用对象。 使用蓝图的三个步骤 1.创建一个蓝图对象
blue = Blueprint(“blue”,name)
2.在这个蓝图对象上进行操作,例如注册路由、指定静态文件夹、注册模板过滤器…
@blue.route(‘/’) def blue_index():
return “Welcome to my blueprint”
3.在应用对象上注册这个蓝图对象
























 app.register_blueprint(blue,url_prefix="/blue") 

141.Flask 和 Django 路由映射的区别?

 在django中,路由是浏览器访问服务器时,先访问的项目中的url,再由项目中的url找到应用中url,这些url是放在一个列表里,遵从从前往后匹配的规则。在flask中,路由是通过装饰器给每个视图函数提供的,而且根据请求方式的不同可以一个url用于不同的作用。 
class getCurrenttime(APIView): def get(self,request): local_time = time.localtime() time_zone =settings.TIME_ZONE temp = { 
   'localtime':local_time,'timezone':time_zone} return Response(temp) 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/215975.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月18日 下午12:51
下一篇 2026年3月18日 下午12:51


相关推荐

  • 使用ipv6内网穿透,实现私有云盘搭建,实现远程控制等功能

    使用ipv6内网穿透,实现私有云盘搭建,实现远程控制等功能

    2021年5月18日
    361
  • lldp协议代码阅读_microsoft,lldp协议[通俗易懂]

    lldp协议代码阅读_microsoft,lldp协议[通俗易懂]第1页共17页竭诚为您提供优质文档/双击可除microsoft,lldp协议篇一:lldp协议配置指导lldp协议交换机配置指导802.lab链接层发现协议(linklayerdiscoveryprotocol),将能够使企业网络的故障查找变得更加容易,并加强网络管理工具在多厂商环境中发现和保持精确网络拓扑结构的能力。该协议可望在下月成为一项正式的标准。lldp是一种邻近发现协议。它为以太网网络设…

    2022年6月2日
    43
  • Coredump(tracedump)

    引言当程序运行的过程中异常终止或崩溃,操作系统会将程序当时的内存状态记录下来,保存在一个文件中(core文件),这种行为就叫做CoreDump或者叫做‘核心转储’,利用coredump可以帮助我们快速定位程序崩溃位置开启coredump终端输入命令:ulimit-a用来显示对进程的一些限制限制,其中第一行表示了core文件最大的大小限制(单位为blocks)默认是…

    2022年4月12日
    93
  • CentOS6.5解决中文乱码与设置字符集

    CentOS6.5解决中文乱码与设置字符集【CleverCode发表在csdn博客中的原创作品,请勿转载,原创地址:http://blog.csdn.net/clevercode/article/details/46377577】1)说明:Windows的默认编码为GBK,Linux的默认编码为UTF-8。在Windows下编辑的中文,在Linux下显示为乱码。为了解决此问题,修改Linux的默认编码为GBK。2)…

    2022年5月25日
    70
  • matplotlib 中的subplot的用法「建议收藏」

    matplotlib 中的subplot的用法「建议收藏」一个figure对象包含了多个子图,可以使用subplot()函数来绘制子图:(首先我没有想明白为啥会有这么多的内容来介绍这一个函数,后来知道了原来这个函数还真的挺多的内容)言简意赅:首先,它的

    2022年8月1日
    12
  • navicat premium 连接sqlserver 端口号配置

    navicat premium 连接sqlserver 端口号配置转载自 https blog csdn net taotoxht article details nbsp navicatpremi nbsp nbsp 连接 sqlserver 端口号是加在 ip 地址后面的用逗号分开

    2026年3月26日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号