lines = open('input.txt', 'r').read().split("\n\n") lines = [line.splitlines() for line in lines] def product(lst): p = 1 for i in lst: p *= i return p class Monkey: def __init__(self, index, items, operator, mul, div, true, false): self.index = index self.items = items self.operator = operator self.mul = mul self.div = div self.true = true self.false = false self.activity = 0 def business(self): throwing = [] at = [] for idx, item in enumerate(self.items): worry = self.op(idx) mod = product([m.div for m in monkeys]) worry = worry % mod target = self.true if self.test(worry) else self.false throwing.append(worry) at.append(target) self.items = [] return (throwing, at) def op(self, itemindex): if self.mul == "old": mult = int(self.items[itemindex]) else: mult = int(self.mul) if self.operator == "*": worry = self.items[itemindex] * mult else: worry = self.items[itemindex] + mult self.activity += 1 return worry def test(self, worrylevel): if worrylevel % self.div == 0: return True else: return False monkeys = [] for l in lines: index = l[0].split(" ")[1][:-1] items = [int(i) for i in l[1].split(":")[1].replace(",","").split(" ")[1:]] operation, mul = l[2].split(" ")[-2:] divisor = int(l[3].split(" ")[-1]) true = int(l[4].split(" ")[-1]) false = int(l[5].split(" ")[-1]) monkeys.append(Monkey(index, items, operation,mul, divisor, true, false)) for round in range(10000): print(round) for monkey in monkeys: if len(monkey.items) == 0: continue else: items, targets = monkey.business() for i in range(len(items)): monkeys[targets[i]].items.append(items[i]) active = [] for m in monkeys: active.append(m.activity) active = sorted(active) print(active) print(active[-1] * active[-2])