-
-
Save sosukeinu/4637433 to your computer and use it in GitHub Desktop.
PYTHON detecting consecutive integers in a list
This file contains 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
# 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]) |
This file contains 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
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