Last active
August 29, 2015 14:06
-
-
Save t-mart/d89881c7a7f37b721b77 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good.