Generate a & ldquo; effective & rdquo; encoding from a list of numbers

advertisements

Possible Duplicate:
How to convert sequence of numbers in an array to range of numbers

I was thinking about this the other day. Say you have the list of numbers:

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 19, 21, 22, 23, 999, 1000, 1001

is there any library or code snipped that will turn the following into something like:

1-13, 19, 21-23, 999-1001

In other words, reduce a full list of numbers to a bunch of ranges or so. I haven't been able to find anything. If no such thing exists, anyone have some ideas for an efficient implementation?


def get_groups(lst):
    slices = [i+1 for i, v in enumerate(zip(lst, l[1:])) if v[0] != v[1]-1]
    slices = [0] + slices + [len(lst)]
    for start, end in zip(slices, slices[1:]):
        yield lst[start:end]

>>> list(get_groups([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 19, 21, 22, 23, 999, 1000, 1001]))
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], [19], [21, 22, 23], [999, 1000, 1001]]

or

def get_ranges(lst):
    slices = [i+1 for i, v in enumerate(zip(lst, l[1:])) if v[0] != v[1]-1]
    slices = [0] + slices + [len(lst)]
    for start, end in zip(slices, slices[1:]):
        yield "%d-%d" % (lst[start], lst[end-1])

>>> list(get_ranges([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 19, 21, 22, 23, 999, 1000, 1001]))
['1-13', '19-19', '21-23', '999-1001']