Skip to content

Instantly share code, notes, and snippets.

@yraksenov
Created November 9, 2015 19:30
Show Gist options
  • Save yraksenov/2da2a3958bda739da556 to your computer and use it in GitHub Desktop.
Save yraksenov/2da2a3958bda739da556 to your computer and use it in GitHub Desktop.
проблема уплотнения списков
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Yura A
"""
def get_input():
"""
получаем строку целых с клавиатуры и превращаем ее
в сортированый массив целых
"""
print 'array>',
raw = raw_input()
result = sorted([int(x) for x in raw.split() if x.isdigit()])
return result
def split(inp):
"""
методом забегания вперед находим непрерывные
последовательности.
добавляем отдельные элементы.
"""
len_inp = len(inp)
result = []
idx = 0
terminate = False
while True:
collect = None
if terminate:
break
for finish in xrange(idx + 1, len_inp):
prev_elem = inp[finish - 1]
next_elem = inp[finish]
if finish + 1 == len_inp:
terminate = True
if prev_elem + 1 == next_elem:
collect = finish
else:
break
if collect:
result.append('{}-{}'.format(inp[idx], inp[collect]))
idx = collect - 1
else:
result.append('{}'.format(inp[idx]))
idx += 1
if idx == len_inp:
terminate = True
return result
if __name__ == '__main__':
INP = get_input()
OUT = split(INP)
print ', '.join(OUT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment