11.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from itertools import zip_longest
  2. from functools import reduce
  3. from operator import mul
  4. def grouper(n, iterable, padvalue=None):
  5. return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)
  6. lines = [line.strip() for line in open("11.input")]
  7. def get_monkeys():
  8. monkeys = []
  9. for chunk in grouper(7, lines):
  10. items = chunk[1].split(":")
  11. items = items[1].strip().split(", ")
  12. exp = chunk[2].split("=")[1]
  13. monkeys.append({
  14. "items": list(map(int, items)),
  15. "op": exp,
  16. "test": int(chunk[3].split(" ")[-1]),
  17. "true": int(chunk[4].split(" ")[-1]),
  18. "false": int(chunk[5].split(" ")[-1]),
  19. "inspects": 0,
  20. })
  21. return monkeys
  22. def run_part(part, rounds, monkeys):
  23. all_prod = reduce(mul, [m["test"] for m in monkeys])
  24. for _ in range(0, rounds):
  25. for monke in monkeys:
  26. for item in monke["items"]:
  27. old = item
  28. new = eval(monke["op"])
  29. monke["inspects"] += 1
  30. if part == 1:
  31. new = new // 3
  32. else:
  33. new %= all_prod
  34. if new % monke["test"] == 0:
  35. target = monke["true"]
  36. else:
  37. target = monke["false"]
  38. monkeys[target]["items"].append(new)
  39. monke["items"] = []
  40. inspects = [m["inspects"] for m in monkeys]
  41. inspects.sort()
  42. print(inspects[-1] * inspects[-2])
  43. run_part(1, 20, get_monkeys())
  44. run_part(2, 10000, get_monkeys())