11_monkeys.py 1.2 KB

12345678910111213141516171819202122232425262728293031
  1. #!/usr/bin/env python3
  2. import sys
  3. from operator import add, mul, pow
  4. from functools import reduce
  5. def parse(f):
  6. for line in f:
  7. if line.startswith(' Starting items:'):
  8. items = tuple(map(int, line.split(':')[1].split(', ')))
  9. opstr, amount = next(f).replace('* old', '** 2').split()[-2:]
  10. op = {'+': add, '*': mul, '**': pow}[opstr], int(amount)
  11. throws = tuple(int(next(f).rsplit(' ', 1)[1]) for _ in range(3))
  12. yield items, op, throws
  13. def business(monkeys, rounds, divisor):
  14. queues = [list(items) for items, _, _ in monkeys]
  15. inspects = [0] * len(monkeys)
  16. modulus = reduce(mul, (div for _, _, (div, _, _) in monkeys))
  17. for _ in range(rounds):
  18. for i, (_, (op, amount), (div, true, false)) in enumerate(monkeys):
  19. items = queues[i]
  20. for item in items:
  21. worry = op(item, amount) // divisor % modulus
  22. queues[false if worry % div else true].append(worry)
  23. inspects[i] += len(items)
  24. items.clear()
  25. return mul(*sorted(inspects)[-2:])
  26. monkeys = list(parse(sys.stdin))
  27. print(business(monkeys, 20, 3))
  28. print(business(monkeys, 10000, 1))