Skip to content

Instantly share code, notes, and snippets.

@sirpengi
Created February 27, 2013 07:14
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 sirpengi/5045885 to your computer and use it in GitHub Desktop.
Save sirpengi/5045885 to your computer and use it in GitHub Desktop.
collapse a list of chars into a range
def collapse(lst):
def chunk(lst):
ret = [lst[0],]
for i in lst[1:]:
if ord(i) == ord(ret[-1]) + 1:
pass
else:
yield ret
ret = []
ret.append(i)
yield ret
chunked = chunk(lst)
ranges = ((min(l), max(l)) for l in chunked)
return ",".join("{0}-{1}".format(*l) if l[0] != l[1] else l[0] for l in ranges)
print collapse(['a', 'b', 'c', 'd', 'f', 'g', 'h', 'q'])
print collapse(['a', 'b', 'c', 'd', 'f', 'g', 'h'])
print collapse(['a', 'c', 'f', 'h'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment