fork download
  1. from itertools import chain, groupby
  2. from random import random
  3.  
  4. maxNumber = 20
  5.  
  6. numbers = [n for n in range(1, maxNumber + 1) if random() < 0.75]
  7.  
  8. def seq2dif(l):
  9. return [l[0]] + [l[i + 1] - l[i] for i in range(len(l) - 1)]
  10.  
  11. def dif2seq(l):
  12. c = 0
  13. s = []
  14.  
  15. for i in range(len(l)):
  16. c += l[i]
  17. s.append(c)
  18.  
  19. return s
  20.  
  21. def flatten(l):
  22. return list(chain.from_iterable(l))
  23.  
  24. def encode(l):
  25. return flatten([[k, len(list(g))] for k, g in groupby(l)])
  26.  
  27. def decode(l):
  28. return flatten([[l[i * 2]] * l[i * 2 + 1] for i in range(int(len(l) / 2))])
  29.  
  30. print(numbers)
  31.  
  32. compressed = encode(seq2dif(numbers))
  33. print(compressed)
  34.  
  35. print(dif2seq(decode(compressed)))
Success #stdin #stdout 0.02s 10328KB
stdin
Standard input is empty
stdout
[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]