What is a Pythonic way to construct intervals from a sequence of integer numbers? E.g. sequence [1, 2, 3, 6, 7, 9]
could be converted to ['1-3', '6-7', '9']
. I have implemented it like this:
def sequence_to_intervals(seq):
intervals = []
interval_start = None
interval_end = None
for i in sorted(seq):
if interval_start is None:
interval_start = i
interval_end = i
elif interval_end + 1 >= i:
interval_end = i
else:
if interval_start == interval_end:
intervals.append(str(interval_start))
else:
intervals.append(f'{interval_start}-{interval_end}')
interval_start = i
interval_end = i
else:
if interval_start == interval_end:
intervals.append(str(interval_start))
else:
intervals.append(f'{interval_start}-{interval_end}')
return intervals
Simple test:
seq = [1, 2, 3, 6, 7, 9]
sequence_to_intervals(seq)
['1-3', '6-7', '9']
Converting intervals back to sequence:
def intervals_to_sequence(intervals):
seq = []
for interval in intervals:
if '-' in interval:
start, stop = interval.split('-')
seq += list(range(int(start), int(stop) + 1))
else:
seq += [int(interval)]
return seq
Simple test:
intervals = ['1-3', '6-7', '9']
intervals_to_sequence(intervals)
[1, 2, 3, 6, 7, 9]
interval_end is None
is never true. \$\endgroup\$