It should be a function that should simplify the output of the information.
For instance, the input is a list of tuples [(2, 7), (7, 8)]
then the output should be [(2, 8)]
I have tried to solve this task but there is somewhere a mistake or perhaps my approach to this problem is incorrect
def func(array):
temparray = []
for i in range(len(array) - 1):
if math.fabs(array[i + 1][0] - array[i][1]) == 0 or math.fabs(array[i + 1][0] - array[i][1]) == 1:
if array[i + 1][1] > array[i][1]:
temparray.append(tuple([array[i][0], array[i + 1][1]]))
else:
temparray.append(tuple([array[i][0], array[i][1]]))
else:
temparray.append(tuple([array[i][0], array[i][1]]))
return temparray
I expect the output of [(3, 5), (4, 8), (10, 12), (9, 10)]
to be [(3, 8), (9, 12)]
, but the actual output is [(3, 8), (4, 8), (10, 12)]
.
here is the solution:
def func(intervals):
si = sorted(intervals, key=lambda tup: tup[0])
merged = []
for tup in si:
if not merged:
merged.append(tup)
else:
b = merged.pop()
if b[1] >= tup[0]:
new_tup = (b[0], max(b[1], tup[1]))
merged.append(new_tup)
else:
merged.append(b)
merged.append(tup)
return merged
For more details -> https://codereview.stackexchange.com/questions/69242/merging-overlapping-intervals