面试题汇总(六)
list1 = ["A",'B',"C"]
list2 = ['X','Y',"Z"]
list3 = [x+y for x in list1 for y in list2]
print(list3)
2、用lambda函数实现递归阶乘
# 方法一
f = lambda n: f(n-1) * n if n >= 2 else 1
print(f(5))
# 方法二
from functools import reduce
res = reduce(lambda x, y: x * y, range(1, 6))
print(res)
3、给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。例1:输入:[1, 3, 5, 6], 5 输出:2 例2:输入:[1, 3, 5, 6], 2 输出:1
def searchInsert(nums, target):
for i in nums:
if i>=target:
return nums.index(i)
if nums[0]>=target:
return 0
else:
return len(nums)
list1 = [1, 3, 5, 6]
res = searchInsert(list1, 7)
print(res)
4、获取某月日历
import calendar
year = input("输入年份:")
month = input("输入月份:")
year = int(year)
month = int(month)
cal = calendar.month(year, month)
print("当前输出月份:" + cal)
5、socket 模块的 socket函数来创建一个 socket 对象
# 辛光华
import socket
socket.socket()
# 袁野
import socket
server = socket.socket() # 创建一个socket对象
ip_port = ('0.0.0.0', 8001) # 给出IP地址和端口号
server.bind(ip_port) # 绑定IP和端口
server.listen(5) # 监听
conn, address = server.accept() # 被动接收请求
while 1:
content = input('服务端:')
conn.send(content.encode('utf-8')) # 发送信息
from_client_msg = conn.recv(1024) # 接收来自客户端的信息
from_client_msg = from_client_msg.decode('utf-8') # 解码来自客户端的信息
print('来自客户端的信息:', from_client_msg)
if from_client_msg == 'bye': # 当客户端的信息为bye时结束聊天
break
conn.close() # 关闭通道
server.close() # 关闭服务端
6、python多进程创建
from multiprocessing import Process
def foo(i):
print ('say hi', i)
if __name__ == '__main__':
for i in range(10):
p = Process(target=foo, args=(i,))
p.start()
7、参考下面代码片段 class Context: TODO pass with Context() as ctx: ctx.do_something()
请在 Context 类下添加代码完成该类的实现。
class Sample:
def __enter__(self):
return self
def __exit__(self, type, value, trace):
print("type:", type)
print("value:", value)
print("trace:", trace)
print(sample)
def do_something(self):
bar = 1
return bar + 10
with Sample() as sample:
sample.do_something()