Skip to content

Instantly share code, notes, and snippets.

@t-mart
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t-mart/d89881c7a7f37b721b77 to your computer and use it in GitHub Desktop.
Save t-mart/d89881c7a7f37b721b77 to your computer and use it in GitHub Desktop.
def list_condense(l):
run_start = None
in_run = False
last_item = None
out = ''
while len(l):
item = l.pop(0)
if not in_run:
run_start = item
in_run = True
out += str(item)
last_item = item
else:
if item == last_item + 1:
if len(l) == 0:
out += '-' + str(item)
else:
last_item = item
else:
if last_item - run_start > 0:
out += '-' + str(last_item)
out += ','
l.insert(0,item)
in_run = False
return out
if __name__ == "__main__":
examples = [[1,2,3,5,7,8,10],
[1,3,5,7,9],
[1,3,5,6,8,9],
[1,2,5,6,7],
range(20)]
for example in examples:
print example
print list_condense(example)
print
# OUTPUT
# [1, 2, 3, 5, 7, 8, 10]
# 1-3,5,7-8,10
# [1, 3, 5, 7, 9]
# 1,3,5,7,9
# [1, 3, 5, 6, 8, 9]
# 1,3,5-6,8-9
# [1, 2, 5, 6, 7]
# 1-2,5-7
# [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# 0-19
@ldong
Copy link

ldong commented Sep 13, 2014

Good.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment