fork download
  1. """
  2. All data is lists of integers.
  3. Every builtin takes a list and returns a list.
  4. Concatenation of builtins is function composition.
  5.  
  6. Given the following tasks:
  7. 1) Reverse the list.
  8. 2) Remove all 0s.
  9. 3) Sort the list.
  10. 4) Duplicate the list (append to itself).
  11. 5) Add 1 to every element.
  12. 6) Rotate 1 step to the left.
  13. 7) Remove all negative elements.
  14. 8) Negate every element.
  15.  
  16. We can achieve these tasks with length-4 programs using 3 different builtins, named E, 0 and 1.
  17. """
  18.  
  19. def interpret(prog, lst):
  20. for char in prog:
  21. lst = interpret_builtin(char, lst)
  22. print(lst)
  23.  
  24. def interpret_builtin(char, lst):
  25. # Builtin E: encode data to "special format" by adding a leading 2.
  26. if char == 'E':
  27. return [2] + lst
  28. # Builtins 0 and 1: if three functions used on data (counting this one), perform task.
  29. num_funcs_used = min(i for i in range(len(lst)) if lst[i] == 2)
  30. if num_funcs_used == 2:
  31. decoded_list = lst[3:]
  32. task_num = int(char) + 2*lst[0] + 4*lst[1]
  33. if task_num == 0:
  34. return decoded_list[::-1]
  35. if task_num == 1:
  36. return [n for n in decoded_list if n != 0]
  37. if task_num == 2:
  38. return list(sorted(decoded_list))
  39. if task_num == 3:
  40. return decoded_list + decoded_list
  41. if task_num == 4:
  42. return [n+1 for n in decoded_list]
  43. if task_num == 5:
  44. return decoded_list[1:] + decoded_list[:1]
  45. if task_num == 6:
  46. return [n for n in decoded_list if n >= 0]
  47. return [-n for n in decoded_list]
  48. # Otherwise, encode self into data.
  49. return [int(char)] + lst
  50.  
  51. interpret("E011", [8,12,-3,0,0,7])
  52. interpret("E100", [8,12,-3,0,0,7])
  53. interpret("E101", [8,12,-3,0,0,7])
Success #stdin #stdout 0.02s 9992KB
stdin
Standard input is empty
stdout
[8, 12, -3, 0, 0, 7, 8, 12, -3, 0, 0, 7]
[9, 13, -2, 1, 1, 8]
[12, -3, 0, 0, 7, 8]