Skip to content

Instantly share code, notes, and snippets.

@vilterp
Created April 27, 2017 22:10
Show Gist options
  • Save vilterp/6f6aa810494f74bec74b7fcc7cf7fc99 to your computer and use it in GitHub Desktop.
Save vilterp/6f6aa810494f74bec74b7fcc7cf7fc99 to your computer and use it in GitHub Desktop.
def append_range(ranges, current_range_start, current_range_end):
if current_range_start == current_range_end:
ranges.append(current_range_start)
else:
ranges.append((current_range_start, current_range_end))
def compress_list_of_integers(ints):
if len(ints) == 0:
return []
ranges = []
current_range_start = ints[0]
current_range_end = None
for value in ints:
if current_range_end == None or value == current_range_end + 1:
current_range_end = value
else:
append_range(ranges, current_range_start, current_range_end)
current_range_start = value
current_range_end = value
append_range(ranges, current_range_start, current_range_end)
return ranges
print compress_list_of_integers([1,2,3,4,5,10,11,12,13,14,21,55,56,57])
# => [(1, 5), (10, 14), 21, 23, 28, (55, 57)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment