input = [x for x in range(5, 51)] + [x for x in range(130, 151)] + [200, 201, 220] beginning, current = 0, 0 output = [] for number in sorted(input): if not beginning: beginning = number current = number continue if number == (current + 1): current = number else: if current == beginning: output.append((current, )) else: output.append((beginning, current)) beginning = number current = number if current == beginning: output.append((current, )) else: output.append((beginning, current)) print(input, ' => ', output)
Standard input is empty
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 200, 201, 220] => [(5, 50), (130, 150), (200, 201), (220,)]