sergeek
А вообще стремновато получается. Может кто-нибудь запостит решение без рекурсии
lst = [2, 3, 4, 5, 6, 10, 20, 45, 77, 78, 79, 87, 96, 97, 98, 0, 123, 124, 125, 126]
lst.sort()
enum_lst = []
enum_tup_lst = []
num_prev = lst[0]
result_lst = []
for enum, num in enumerate(lst[1:]):
if num - num_prev == 1 and num != lst[-1]:
enum_lst.append(enum)
num_prev = num
elif len(enum_lst) > 1:
enum_lst.append(enum)
if num == lst[-1] and num - lst[-2] == 1:
enum_lst.append(enum+1)
enum_tup_lst.append([enum_lst[0], enum_lst[-1]])
enum_lst = []
num_prev = num
else:
num_prev = num
it = iter(enumerate(lst))
borders_it = iter(enum_tup_lst)
border = next(borders_it)
for enum, num in it:
try:
if border[0] <= enum <= border[1]:
result_lst.append( ':'.join( [str( lst[border[0]] ), str( lst[border[1]] )] ) )
for i in xrange(border[1] - enum):
next(it)
border = next(borders_it)
else:
result_lst.append(num)
except StopIteration:
for enum, num in it:
result_lst.append(num)
print(lst)
print(result_lst)
[0, 2, 3, 4, 5, 6, 10, 20, 45, 77, 78, 79, 87, 96, 97, 98, 123, 124, 125, 126]
[0, '2:6', 10, 20, 45, '77:79', 87, '96:98', '123:126']
[1, 2, 3, 4, 5, 6, 10, 123, 346]
['1:6', 10, 123, 346]