Unfolding the lists
.py
Unfold the list with ranges, sort and regroup
o = ['12-15', '40003', '40012', '71842-71844', '71848-71851',
'71853-54', '72717-72721', '72724-72732', '72734', '72787',
'68344', '46', '48', '49', '68351-68354', '68358', '59',
]
def r(s):
if '-' in s:
a, b = map(int, s.split('-'))
if b < a:
sa, sb = map(str, (a, b))
la, lb = map(len, (sa, sb))
sb = sa[:la-lb] + sb
b = int(sb)
return list(range(a, b+1))
else:
return [int(s),]
def r2(q):
b = q.pop()
while True:
try:
a = b
prev = None
b = q.pop()
prev = a
while (b == prev + 1):
prev = b
b = q.pop()
if prev and a!=prev:
yield '-'.join(map(str, (a, prev)))
else:
yield str(a)
except IndexError:
if prev and a!=prev:
yield '-'.join(map(str, (a, prev)))
return
else:
yield str(a)
return
z = []
for x in o:
z.extend(r(x))
for i in range(len(z) - 1):
a, b = z[i], z[i+1]
if a>1000 and b < 1000:
sa, sb = map(str, (a, b))
la, lb = map(len, (sa, sb))
sb = sa[:la-lb] + sb
b = int(sb)
z[i+1] = b
# We have a full unwrapped list here (z)
z1 = sorted(set(z))
# Saved to z1
z = sorted(set(z), reverse=True)
z2 = list(r2(z))
# So we have new folded list here (z2)