Skip to content

Instantly share code, notes, and snippets.

@danshultz
Created November 2, 2012 17:41
Show Gist options
  • Save danshultz/4003053 to your computer and use it in GitHub Desktop.
Save danshultz/4003053 to your computer and use it in GitHub Desktop.
Python Number List to Text Ranges
# Ref from http://stackoverflow.com/questions/2361945/detecting-consecutive-integers-in-a-list
from itertools import groupby
from operator import itemgetter
class PageRange(object):
@staticmethod
def to_text_range(array_of_numbers):
text_buffer = []
for k, g in groupby(enumerate(sorted(array_of_numbers)), lambda (i,x):i-x):
val = PageRange._create_text(map(itemgetter(1), g))
text_buffer.append(val)
return ','.join(text_buffer)
@staticmethod
def _create_text(run):
if len(run) == 1:
return run[0].__str__()
return "{0}-{1}".format(run[0], run[-1])
import unittest
from nose.tools import *
class PageRangeSinglePageTestCase(unittest.TestCase):
def test_full_range(self):
test = PageRange.to_text_range(range(1,51))
assert_equal("1-50", test)
def test_ranges_and_single_pages(self):
pr = [1,5,9,10,11] + range(20, 31) + [99,105,120] + range(150, 161) + [800]
test = PageRange.to_text_range(pr)
assert_equal("1,5,9-11,20-30,99,105,120,150-160,800", test)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment