Skip to content

Instantly share code, notes, and snippets.

@swizzlevixen
Created June 1, 2014 04:24
Show Gist options
  • Save swizzlevixen/03c45bd9d23a162114ff to your computer and use it in GitHub Desktop.
Save swizzlevixen/03c45bd9d23a162114ff to your computer and use it in GitHub Desktop.
De-pack string representation of page ranges into an int list, sort, and re-pack
def depack(value):
"""
:type value: str
"""
print "depack"
page_list = []
for part in value.split(','):
if '-' in part:
a, b = part.split('-')
a, b = int(a), int(b)
page_list.extend(range(a, b + 1))
else:
a = int(part)
page_list.append(a)
return page_list
def repack(page_list):
"""
Returns a string representation from integers in a list
:type value: list
"""
print "repack"
# Need to sort the list first
sorted_values = sorted(page_list, key=int)
ranges = []
for key, group in groupby(enumerate(sorted_values), lambda (index, item): index - item):
group = map(itemgetter(1), group)
if len(group) > 1:
ranges.append(xrange(group[0], group[-1])) # under 3.x, switch to "range"
else:
ranges.append(group[0])
ranges_strings = []
for item in ranges:
if isinstance(item, xrange): # This only works under Python 2.x - under 3.x, switch to "range"
# 1-2
range = "%d-%d" % (item[0], item[-1]+1)
ranges_strings.append(range)
else:
ranges_strings.append(str(item))
return ", ".join([unicode(s) for s in ranges_strings])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment