我的一个朋友通过了我最近得到的一个面试问题,我对解决方案的态度不太满意.问题如下:
一般而言,在列表的排序或重叠方面没有"陷阱".
例:
a = [[0, 2], [5, 10], [13, 23], [24, 25]]
b = [[1, 5], [8, 12], [15, 18], [20, 24]]
Run Code Online (Sandbox Code Playgroud)
预期产量:
[[1, 2], [5, 5], [8, 10], [15, 18], [20, 24]]
我的懒惰解决方案涉及将范围列表扩展为整数列表,然后执行集合交集,如下所示:
def get_intersection(x, y):
x_spread = [item for sublist in [list(range(l[0],l[1]+1)) for l in x] for item in sublist]
y_spread = [item for sublist in [list(range(l[0],l[1]+1)) for l in y] for item in sublist]
flat_intersect_list = list(set(x_spread).intersection(y_spread))
...
Run Code Online (Sandbox Code Playgroud)
但我想有一个既可读也有效的解决方案. …