#!/usr/bin/python3 import fileinput # Monkey data structures: items = [] operator = [] operand = [] divtest = [] trueto = [] falseto = [] count = [] modulo = 1 def monkey(m): global items, operator, operand, divtest, trueto, falseto, count, modulo for i in items[m]: count[m] += 1 if operator[m] == '+': i += operand[m] elif operator[m] == '*': i *= operand[m] elif operator[m] == '^': i *= i # i //= 3 i %= modulo if i % divtest[m] == 0: items[trueto[m]].append(i) else: items[falseto[m]].append(i) items[m] = [] def round(): global items for m in range(0, len(items)): monkey(m) def show(): global items for m in range(0, len(items)): print("Monkey %d: %s" % (m, items[m])) print('') for line in fileinput.input(): line = line.rstrip() if line.startswith('Monkey'): m = int(line.split(' ')[1].rstrip(':')) items.append([]) operator.append('') operand.append(0) divtest.append(0) trueto.append(0) falseto.append(0) count.append(0) elif line.startswith(' Starting'): items[m] = list(map(int, line.split(': ')[1].split(', '))) elif line.startswith(' Operation'): if line.endswith('old * old'): operator[m] = '^' # squared operand[m] = 0 # ignored else: words = line.lstrip().split(' ') operator[m] = words[-2] operand[m] = int(words[-1]) elif line.startswith(' Test'): divtest[m] = int(line.split('by ')[1]) modulo *= divtest[m] elif line.startswith(' If true'): trueto[m] = int(line.split('monkey ')[1]) elif line.startswith(' If false'): falseto[m] = int(line.split('monkey ')[1]) # show() for i in range(0, 10000): round() count.sort(reverse=True) print(count[0] * count[1])