面试技巧

关注公众号 jb51net

关闭
IT专业知识 > IT职场规划 > 面试技巧 >

Python经典面试题与参考答案集锦

kaichenkai

一些面试题

1.列表的遍历问题(0507)

list_1 = [10, 20, 30, 40, 50]
# 不能对一个列表同时进行 遍历 和 增删元素
for element in list_1:
 print(element)
 if element == 30 or element == 40:
 list_1.remove(element)
print(list_1)
# 改进
temp_list = list()
# 先遍历列表,记录下需要增删的元素
for element in list_1:
 print(element)
 if element == 30 or element == 40:
  temp_list.append(element)
# 遍历完列表,再对需要增删的内容进行逐一处理
for element in temp_list:
 list_1.remove(element)
print(list_1)

2.字典排序 (0530)

# 题目1
# 按照score的值进行排序。

list_a = [
    {"name": "p1", "score": 100},
    {"name": "p2", "score": 10},
    {"name": "p3", "score": 30},
    {"name": "p4", "score": 40},
    {"name": "p5", "score": 60},
]
print(sorted(list_a, key=lambda a: a["score"], reverse=False))

# 题目2
# 一行代码 通过filter 和 lambda 函数输出以下列表索引为奇数的对应的元素
list_b = [12, 232, 22, 2, 2, 3, 22, 22, 32]

方法一:

new_list=[x[1]   for  x  in  fliter(lambdy x:x[0]%2==1,enumerate(list_b))]

方法二:

for index, element in enumerate(list_b):
    print("") if index % 2 == 0 else print(element)

3.给定三个整数 a, b, c 求和 ,求和之前需要删除里面相同的整数

示例:

loneSum(1, 2, 3)    ->   6
loneSum(3, 2, 3)    ->   2
loneSum(3, 3, 3)    ->   0

loneSum1 = (1, 2, 3)
loneSum2 = (3, 2, 3)
loneSum3 = (3, 3, 3)

counter = int()
for element in loneSum1:
    if loneSum1.count(element) == 1:
        counter += element
print(counter)

4.给出一个字符串,找出头尾的镜像字符串,即从头正序,从尾倒叙相同的字符串;

示例:

mirrorEnds("abXYZba")    -> "ab"
mirrorEnds("abca")       -> "a"
mirrorEnds("aba")        -> "aba"

def main(source_str):
    reverse_str = source_str[::-1]
    for i in range(len(source_str)):
        if reverse_str[:(i+1)] != source_str[:(i+1)]:
            return source_str[:i]
        if reverse_str == source_str:
            return source_str
            
if __name__ == '__main__':
 print(main(mirrorEnds))

5.给定一个整数系列 N1, N2…;以及整数M, M是整数系列中的最大数; 从整数系列中取三个数, 可以重复取,要求三个数的和为M。 求所有的可能结果, 并剔除具有相同的结果,得到排序不同的结果。

示例:数列N: [1, 3, 5, 7, 9, 11, 13, 15], 和 M 为17, 返回结果是
[1, 1, 15], [1, 3, 13], [1, 5, 11], [1, 7, 9], [3, 3, 11], [3, 5, 9], [3, 7, 7], [5, 5, 7]

num_list = [1, 3, 5, 7, 9, 11, 13, 15]
M = 17
for i in range(len(num_list)):
    for j in range(i, len(num_list)):
        for k in range(j, len(num_list)):
            if num_list[i] + num_list[j] + num_list[k] == M:
                print((num_list[i], num_list[j], num_list[k]))

6.MRO继承的问题

求三次输出的 Parent.x, Child1.x, Child2.x 分别是多少?

lass 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)
# 提示:print(Child1.__mro__)
#答案:1,1,1  1,2,1  3,2,3 

7.参数传递的问题

第一题

class Counter():
 def __init__(self, count=0):
  self.count = count
def main():
 c = Counter()
 c.name = "zhangsan"
 times = 0
 for i in range(10):
  increment(c, times)
 print("count is {0}".format(c.count))
 print("times is {0}".format(times))
def increment(c, times):
 times += 1
 c.count += 1
if __name__ == "__main__":
 main()  
#答案:
# count is 10
# times is 0

第二题

class Count(object):
    def __init__(self, count=0):
        self.count = count
def main():
    c = Count()
    n = 1
    m(c, n)
    print("count is {0}".format(c.count))
    print("n is {0}".format(n))
def m(c, n):
    c = Count(5)
    n = 3
if __name__ == '__main__':
    main() 
#答案:
# count is 0
# n is 1

8.装饰器/闭包面试题(0615)

def outFun(a):
 def inFun(x):
  return a * x
 return inFun
flist1 = [outFun(a) for a in range(3)]
for func in flist1:
 print(func(1))
# fist2 = [lambda x:a*x for a in range(3)]
flist2 = [lambda x:a*x for a in range(4)]
for func in flist2:
 print(func(2))
# 答案: 0 1 2, 6 6 6 6

9.字典排序题(zrc)

s = [{1: "a"}, {3: "c"}, {2: "b"}]

请按照字母acsii码排序

print(sorted(s, key = lambda x: tuple(x.values())[0]))

 或
 

print(sorted(s, key = lambda x: list(x.values())[0]))

sorted 语法:

sorted(iterable[, cmp[, key[, reverse]]])

参数说明:

返回重新排序的列表。

10.冒泡排序题(zrc)

def sor():
    li=[{1:"b"},{3:"c"},{2:"a"}]
    for i in range(len(li)):
        for j in range(len(li) - i - 1):
            v1 = [value for value in list(li[j].values())][0]
            v2 = [value for value in list(li[j+1].values())][0]
            print(v1,v2)
            if v1 > v2:
                li[j],li[j+1] = li[j+1],li[j]
    return li
ret = sor()
print(ret)

11.二分法查找(zrc)

def bin_search(data_set, value):
 low = 0; high = len(data_set) - 1
 while True:
  mid = (low + high) // 2
  if data_set[mid] > value:
   high = mid - 1
  elif data_set[mid] < value:
   low = mid + 1
  else:
   a = b = mid
   while data_set[a] == value and a >= 0:
    a -= 1
   while data_set[b] == value and b < len(data_set) - 1:
    b += 1
   return (a+1, b)
ret = bin_search([8,8,8,8], 8)
print(ret)

12.a=[1,2,3,4,5,6],打印出所有以偶数为key,奇数为值的字典

print({key: value for key, value in zip([i for i in a if i % 2 == 0], [i for i in a if i % 2 != 0])})

13.写一个函数实现阶乘

def factorial(num):
    counter = 1
    for i in range(1, num+1):
        counter *= i
    return counter
print(factorial(5))

14.有字符串a=‘hsfbsadgasdgvnhhhadhaskdhwqhcjasd’,求出现次数最多的前四个

第一种解法:

def search(a):
    # 省略校验逻辑
    # 生成包含 element 和 count 数据的集合
    data_set = {(element, count) for element, count in zip(a, [a.count(i) for i in a])}
    print(data_set)
    # 转换成列表类型,进行倒序排序
    data_list = list(data_set)
    new_data_list = sorted(data_list, key=lambda x: x[1], reverse=True)
    # 取出前四名
    new_data_list = new_data_list[0:4]
    # 拼接字符串
    return "".join([i[0] for i in new_data_list])
print(search(a))

第二种简单解法:

a = 'hsfbsadgasdgvnhhhadhaskdhwqhcjasd'
# 导入Counter模块
from collections import Counter
# 创建对象
count = Counter(a)
# 获取出现频率最高的四个字符
print(count.most_common(4))
# 输出:[('h', 7), ('s', 5), ('a', 5), ('d', 5)]

15.sorted排序

if other_allocated_amount:
    data_list.append({
        "shop_id": 0,
        "shop_name": "其他",
        "destination": 2,
        "current_storage": 0,
        "demand_amount": 0,
        "allocated_amount": other_allocated_amount,
        "priority": 0,
        "negative_order": 0
    })
# 按优先级排序
data_list = sorted(data_list, key=lambda d: d["priority"], reverse=True)
shop_order = {"仓库": -999, "总部": 1, "刘园": 2, "侯台": 3,
              "咸水沽": 4, "华明": 5,
              "大港": 6, "杨村": 7, "新立": 8, "大寺": 9, "汉沽": 10,
              "沧州": 11, "静海": 13, "芦台": 14, "工农村": 15, "唐山": 16, "廊坊": 17,
              "哈尔滨": 18, "西青道": 19, "双鸭山": 20, "承德": 21,
              "张胖子": 22, "固安": 23, "燕郊": 24, "胜芳": 25, "蓟县": 26, }
data_list = sorted(data_list, key=lambda d: shop_order.get(d["shop_name"], 999))