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()
Given a data file, I had to create tuples, store tuples in list, sort the list and replace each pair of overlapping tuples with a single tuple.Then print list of non intersecting tuples.
But now I want to know how to print the non-intersecting intervals in increasing order of the size of the intervals. If two intervals are of the same size then print the two intervals in ascending order of their lower ends. So the output would look like:
Non-intersecting Intervals: (-4,3) (4,7) (10,15)
Non-intersecting Intervals in order of size: (4, 7) (10, 15) (-4, 3)