def merge_intervals(intervals): # If the list is empty, return None if not intervals: return None result = [] # Adding the first interval from the input list (v) to the output list (result) result.append([intervals[0][0], intervals[0][1]]) for i in range(1, len(intervals)): # Last interval present in the output list last_added_interval = result[len(result) - 1] # Variables to store the start and end times of the current interval cur_start = intervals[i][0] cur_end = intervals[i][1] print("\n\t\t\tCurrent input interval:", "[", cur_start, ",", cur_end, "]", "\n") # The end time of the last interval present in the output list prev_end = last_added_interval[1] print("\t\t\t{:<4}{:<10}{:<4}{:<9}{:<4}".format( "|", "cur_start", "|", "cur_end", "|")) print("\t\t\t", "-"*26) print("\t\t\t{:<4}{:<10}{:<4}{:<9}{:<4}".format( "|", cur_start, "|", cur_end, "|")) return result # Driver code def main(): all_intervals = [ [[1, 5], [3, 7], [4, 6]], [[1, 5], [4, 6], [6, 8], [11, 15]], [[3, 7], [6, 8], [10, 12], [11, 15]], [[1, 5]], [[1, 9], [3, 8], [4, 4]], [[1, 2], [3, 4], [8, 8]], [[1, 5], [1, 3]], [[1, 5], [6, 9]], [[0, 0], [1, 18], [1, 3]] ] for i in range(len(all_intervals)): print(i + 1, ". Intervals to merge: ", all_intervals[i], sep="") result = merge_intervals(all_intervals[i]) print("-"*100) if __name__ == '__main__': main()