def ranges iterable iterable iter iterable start stop iterable next fo

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
def ranges(iterable):
iterable = iter(iterable)
start = stop = iterable.next()
for cur in iterable:
stop += 1
if cur != stop:
yield yield_range(start, stop, '-')
start = stop = cur
yield yield_range(start, stop, '-')
def yield_range(start, stop, delimiter):
if start == stop:
return str(stop)
else:
return "%d%s%d" % (start, delimiter, stop)
if __name__ == '__main__':
print list(ranges([1, 2, 3, 5, 6, 11]))
print list(ranges([1, 3, 4, 12, 13]))
print list(ranges([1, 2, 3, 4, 7, 8]))