13.py 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from itertools import zip_longest
  2. from functools import cmp_to_key
  3. def grouper(n, iterable, padvalue=None):
  4. return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
  5. lines = [eval(line.strip()) for line in open("13.input") if line.strip() != ""]
  6. pairs = list(grouper(2, lines))
  7. def comp(pair):
  8. left, right = pair
  9. if isinstance(left, int) and isinstance(right, int):
  10. if left == right:
  11. return None
  12. else:
  13. return left < right
  14. elif isinstance(left, list) and isinstance(right, list):
  15. for p in zip_longest(left, right, fillvalue=None):
  16. l, r = p
  17. if l is None:
  18. return True
  19. elif r is None:
  20. return False
  21. elif comp(p) is not None:
  22. return comp(p)
  23. else:
  24. continue
  25. else:
  26. if isinstance(left, int):
  27. return comp(([left], right))
  28. else:
  29. return comp((left, [right]))
  30. s = 0
  31. for i, pair in enumerate(pairs):
  32. if comp(pair):
  33. s += 1 + i
  34. print("Part 1:", s)
  35. packets = lines
  36. packets.append([[2]])
  37. packets.append([[6]])
  38. packets.sort(key=cmp_to_key(lambda a, b: 1 if comp((a, b)) else -1), reverse=True)
  39. prod = 1
  40. for i, packet in enumerate(packets):
  41. if packet == [[2]] or packet == [[6]]:
  42. prod *= (1 + i)
  43. print("Part 2:", prod)