def mergeoverlapping(initialranges):
i = sorted(set([tuple(sorted(x)) for x in initialranges]))
f = [i[0]]
for c, d in i[1:]:
a, b = f[-1]
if c<=b<d:
f[-1] = a, d
elif b<c<d:
f.append((c,d))
else:
pass
return f
def main():
#open file for reading
list_of_Tups = []
with open("intervals.txt") as in_file:
for line in in_file:
int_list = [int(i) for i in line.split()]
line = int_list
list_of_Tups.append(line)
list_of_Tups.sort()
answer = list(mergeoverlapping(list_of_Tups))
print("Non-intersecting Intervals:")
for i in range (len(answer)):
print(answer[i])
main()
给定一个数据文件,我必须创建元组,在列表中存储元组,对列表进行排序,并用一个元组替换每对重叠的元组。然后打印非交叉元组的列表。
但现在我想知道如何按照间隔大小的递增顺序打印非交叉间隔。如果两个间隔具有相同的大小,则按其下端的升序打印两个间隔。所以输出看起来像:
非交叉间隔: (-4,3) (4,7) (10,15)
按大小顺序的非交叉间隔: (4,7) (10,15) (-4,3)
答案 0 :(得分:0)
假设:
intervals = [(-25, -14), (-10, -3), (2, 6), (12, 18), (22, 30)]
然后就像你已经排序一样,你只需根据大小进行排序。
# First sort in ascending order in relation to lower
intervals.sort(key=lambda interval: interval[0])
# Then sort in ascending order in relation to size
intervals.sort(key=lambda interval: abs(interval[0] - interval[1]))
然后print(intervals)
输出:
[(2, 6), (12, 18), (-10, -3), (22, 30), (-25, -14)]
如果给定(-4, 3), (4, 7), (-2, 1)
,则会产生(-2, 1), (4, 7), (-4, 3)
(大小为3, 3, 7
)。所以它正确地根据较低的尺寸进行排序。