import os input = open(os.path.dirname(__file__) + "/input.txt", "r").read().split('\n\n') class Operation: def __init__(self, operand, y: int): self.operand: str = operand self.y: int = y def operate(self, input: int) -> int: i = int(input) j = 0 if self.y == 'old': j = i else: j = int(self.y) if (self.operand == '+'): return i + j if (self.operand == '*'): return i * j class Monkey: def __init__(self, monkeyid: int, items, operation, testNumber: int, actionTrue: int, actionFalse: int): self.monkeyid = monkeyid self.items = items op = operation.split() self.operation = Operation(op[1], op[2]) self.testNumber = testNumber self.actionTrue = int(actionTrue) self.actionFalse = int(actionFalse) self.inspections = 0 def inspect(self, worryDivider: int, p2: bool = False): self.inspections += 1 item: int = self.items.pop(0) worryScore = self.operation.operate(item)//worryDivider if (p2): worryScore %= lcm if worryScore % self.testNumber == 0: return (self.actionTrue, worryScore) else: return (self.actionFalse, worryScore) def __str__(self): return "Monkey " + str(self.monkeyid) + ": "+str(self.items)+" true: "+str(self.actionTrue)+" false: "+str(self.actionFalse)+" inspect: "+str(self.inspections) monkeys = {} for l in input: data = l.splitlines() monkeyid = data[0].split()[1][0] items = [] itemline = data[1].strip().split(': ') for i in itemline[1].strip().split(', '): items.append(int(i)) operation = data[2].split('=')[1] test = int(data[3].split()[3]) optrue = int(data[4].strip().split()[5]) opfalse = int(data[5].strip().split()[5]) m = Monkey(monkeyid, items, operation, test, optrue, opfalse) monkeys[int(monkeyid)] = m lcm = 1 divs = [] for m in monkeys: divs.append(monkeys[m].testNumber) for x in divs: lcm = lcm*x def printMonkeys(): for m in monkeys: print(monkeys[m]) def process(rounds: int, worryDivider: int, p2: bool = False): for round in range(1, rounds+1): for m in monkeys: while len(monkeys[m].items) != 0: (nextmonkey, item) = monkeys[m].inspect(worryDivider, p2) monkeys[nextmonkey].items.append(item) tot = [] for m in monkeys: tot.append(monkeys[m].inspections) tot.sort() return tot[-1]*tot[-2] print(process(20, 3)) print(process(10000, 1, True))