from itertools import chain, groupby from random import random maxNumber = 20 numbers = [n for n in range(1, maxNumber + 1) if random() < 0.75] def seq2dif(l): return [l[0]] + [l[i + 1] - l[i] for i in range(len(l) - 1)] def dif2seq(l): c = 0 s = [] for i in range(len(l)): c += l[i] s.append(c) return s def flatten(l): return list(chain.from_iterable(l)) def encode(l): return flatten([[k, len(list(g))] for k, g in groupby(l)]) def decode(l): return flatten([[l[i * 2]] * l[i * 2 + 1] for i in range(int(len(l) / 2))]) print(numbers) compressed = encode(seq2dif(numbers)) print(compressed) print(dif2seq(decode(compressed)))
Standard input is empty
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 15, 16, 17, 18, 19] [1, 11, 4, 1, 1, 4] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 15, 16, 17, 18, 19]