Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
one pass over sorted list solution in Speedy category for Create Intervals by Leonix
def create_intervals(data):
# Convert `set` into a sorted `list` of integers
data = sorted(data)
# A trick to force additional loop iteration to add last interval
data.append(float("Inf"))
# `last_i` is the element before `i` in list.
# `result` contains all the intervals before the one `i` belongs to.
# `current_interval_start` is the start of an interval `i` belongs to.
result = []
last_i = current_interval_start = data.pop(0)
# Loop over integers in ascending order, maintaining invariants described above
for i in data:
if i > last_i + 1:
# Found a break: add last interval, remember start of new interval
result.append((current_interval_start, last_i))
current_interval_start = i
last_i = i
return result
April 4, 2019
Comments: