python面试(十四)
1、下面代码会输出什么?
map(lambda x:x*x,[y for y in range(3)])
[0, 1, 4]
2、下面代码会输出什么?
def f(x, l = [] )
for i in range(x):
l.append(i*i)
print l
f(2)
f(3,[3,2,1])
f(3)
1、[0, 1] 2、[3, 2, 1, 0, 1, 4] 3、[0, 1, 0, 1, 4]
3、数是数据结构中非常重要的一种,主要的用途是用来提高效率,对于要重复查找的情况效果更佳,二叉树是其中最常见的结构之一,示例如下:
层级遍历: 0 1 2 3 4 5 6 7 8 9
先序遍历:0 1 3 7 8 4 9 2 5 6
中序遍历:7 3 8 1 9 4 0 5 2 6
后序排列:7 8 3 9 4 1 5 6 2 0
class Node(object): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right
r为Node类型的根节点
实现函数traverse(r)输出先序遍历结果,输出部分使用print r.data即可
node7 = Node(7) node8 = Node(8) node9 = Node(9) node3 = Node(3,node7,node8) node4 = Node(4,node9) node5 = Node(5) node6 = Node(6) node1 = Node(1,node3,node4) node2 = Node(2,node5,node6) node0 = Node(0,node1,node2) def traverse(r): print(r.data) if r.left: traverse(r.left) if r.right: traverse(r.right)
4、有一个3G大小的文件,文件每行一个string,内容为酒店的id和一个图片的名字,使用“\t”分割
示例:ht_1023134 + "\t" + hidfadsfadsfdfadsf2r234523,jpg
表示的是一个酒店包含的一张图片,统计含有图片数量为[20,无穷大]的酒店id,含有图片数量为[10,20]的酒店id、含有图片数量为[10,5]的酒店id,含有图片数量为[0,5]的酒店id,并将结果输出到文件中
0-5 + “\t” + id1 + “\t” + id2 + .....
5-10 + “\t” + id1 + “\t” + id2 + .....
10-20 + “\t” + id1 + “\t” + id2 + .....
20-无穷大 + “\t” + id1 + “\t” + id2 + .....
from collections import Counter count_dict = {} cou = Counter() with open('a.txt', encoding='utf-8') as f: for line in f: hotel, image = line.split() hotel_id = hotel.split('_')[1] cou.update({hotel_id,1}) if hotel_id in count_dict: count_dict[hotel_id] += 1 else: count_dict[hotel_id] = 1 del cou[1] zero_five = ['0-5'] five_ten = ['5-10'] ten_twenty = ['10-20'] twenty_infinite = ['10-去穷大'] for hotel_id,count in count_dict.items(): if count < 5 : zero_five.append(hotel_id) elif count < 10 : five_ten.append(hotel_id) elif count < 20: ten_twenty.append(hotel_id) else: twenty_infinite.append(hotel_id) with open('b.txt','w',encoding='utf-8') as b: b.write('\t'.join(zero_five)) b.write('\n') b.write('\t'.join(five_ten)) b.write('\n') b.write('\t'.join(ten_twenty)) b.write('\n') b.write('\t'.join(twenty_infinite))
人,从刚出生来到这个世界,便开始探索这个世界。累了就歇会,精神了就继续探索,直至死亡。