Skip to content

Instantly share code, notes, and snippets.

@jclement
Last active December 12, 2015 01:49
Show Gist options
  • Select an option

  • Save jclement/4694033 to your computer and use it in GitHub Desktop.

Select an option

Save jclement/4694033 to your computer and use it in GitHub Desktop.
Quick little algorithm to chop up an array into an array of contiguous ranges.
samples=[
# =======================================
# input, expected result pairs
# =======================================
# empty list
([], []),
# single digit
([1], [(1,1)]),
# basic range
([1,2,3], [(1,3)]),
# should handle duplicates
([1,2,3,2], [(1,3)]),
# order shouldn't matter
([3,2,1], [(1,3)]),
# basic two ranges
([1,2,3,6,7,8], [(1,3),(6,8)]),
# multiple ranges and single digits
([1,2,3,5,7,8,11], [(1,3),(5,5),(7,8),(11,11)]),
# bunch of single digits
([1,5,10], [(1,1), (5,5), (10,10)]),
]
def segment(array):
"""
Segment an array of numbers into continguous ranges. """
if len(array) ==0: return []
array.sort()
result=[]
mark_low = array[0]
mark_high = array[0]
for v in array:
if v-mark_high > 1:
result.append((mark_low, mark_high))
mark_low=v
mark_high=v
else:
mark_high=v
result.append((mark_low, mark_high))
return result
for tInput, tResult in samples:
result = segment(tInput)
if tResult != result:
print "Error: %s => %s (expected %s)" % (tInput, result, tResult)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment