Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Two solutions solution in Clear category for Create Intervals by Phil15
# Sorted data version.
def create_intervals(data):
res, data = [], sorted(data)
for i, n in enumerate(data):
if i and data[i - 1] == n - 1:
res[-1][1] = n
else:
res.append([n, n])
return list(map(tuple, res))
# Dict version.
def create_intervals(data): # It would fit well an iterator "data".
starts, ends = {}, {} # {start: end}, {end: start}
for n in data:
start, end = ends.pop(n - 1, n), starts.pop(n + 1, n)
starts[start], ends[end] = end, start
return sorted(starts.items())
if __name__ == '__main__':
assert create_intervals({1, 2, 3, 4, 5, 7, 8, 12}) == [(1, 5), (7, 8), (12, 12)]
assert create_intervals({1, 2, 3, 6, 7, 8, 4, 5}) == [(1, 8)]
assert create_intervals({1, 3, 7}) == [(1, 1), (3, 3), (7, 7)]
assert create_intervals({7, 9, 10, 11, 12}) == [(7, 7), (9, 12)]
assert create_intervals({1, 3, 5, 7}) == [(1, 1), (3, 3), (5, 5), (7, 7)]
assert create_intervals(set()) == []
assert create_intervals({1}) == [(1, 1)]
assert create_intervals({8, 7}) == [(7, 8)]
assert create_intervals({6, 9, 1, 7}) == [(1, 1), (6, 7), (9, 9)]
assert create_intervals({8, 9, 6, 7}) == [(6, 9)]
Feb. 28, 2020
Comments: