Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Merge Intervals by Kurush
def merge_intervals(intervals):
"""
Merge overlapped intervals.
"""
merged = []
while intervals != []:
if merged == []:
merged.append(list(intervals.pop(0)))
continue
new_elem = intervals.pop(0)
if new_elem[0] > merged[-1][1] + 1: merged.append(list(new_elem))
elif new_elem[1] >= merged[-1][1] + 1: merged[-1][1] = new_elem[1]
merged = list(map(lambda elem: tuple(elem), merged))
return merged
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert merge_intervals([(1, 4), (2, 6), (8, 10), (12, 19)]) == [(1, 6), (8, 10), (12, 19)], "First"
assert merge_intervals([(1, 12), (2, 3), (4, 7)]) == [(1, 12)], "Second"
assert merge_intervals([(1, 5), (6, 10), (10, 15), (17, 20)]) == [(1, 15), (17, 20)], "Third"
print('Done! Go ahead and Check IT')
Feb. 25, 2019