1
0
Fork 0

11: Py: Cleanup and avoid eval()

This commit is contained in:
Mia Herkt 2022-12-11 21:47:08 +01:00
parent 0a9f3c078d
commit ba1ca8492d
Signed by: mia
GPG Key ID: 72E154B8622EC191
1 changed files with 44 additions and 38 deletions

View File

@ -3,45 +3,51 @@
import sys import sys
from copy import deepcopy from copy import deepcopy
from math import prod from math import prod
from operator import add, mul
def monkey_business(monkeys, rounds, part2):
monkeys = deepcopy(monkeys)
ohmygodihateyoueric = prod(m["test"] for m in monkeys)
for it in range(rounds):
for m in monkeys:
for old in m["items"]:
m["count"] += 1
new = m["op"](old)
if part2:
new %= ohmygodihateyoueric
else:
new //= 3
monkeys[m[not (new % m["test"])]]["items"].append(new)
m["items"].clear()
return prod(sorted(m["count"] for m in monkeys)[-2:])
def op2func(opstr):
params = opstr.split()
op = add if params[1] == "+" else mul
if params[2] == "old":
func = lambda old: op(old, old)
else:
func = lambda old: op(old, int(params[2]))
return func
monkeys = [] monkeys = []
for l in sys.stdin: for a, b in [l.strip().split(":") for l in sys.stdin if ":" in l]:
l = l.strip() match a.split():
if l.startswith("M"): case ["Monkey", _]:
monkeys.append({}) monkeys.append({})
monkeys[-1]["count"] = 0 monkeys[-1]["count"] = 0
elif l.startswith("S"): case ["Starting", "items"]:
monkeys[-1]["items"] = [int(x) for x in l[16:].split(", ")] monkeys[-1]["items"] = [int(x) for x in b.split(", ")]
elif l.startswith("O"): case ["Operation"]:
monkeys[-1]["op"] = l[17:] monkeys[-1]["op"] = op2func(b.split(" = ")[1])
elif l.startswith("T"): case ["Test"]:
monkeys[-1]["test"] = int(l[19:]) monkeys[-1]["test"] = int(b.rsplit(" ", 1)[-1])
elif l.startswith("If t"): case ["If", condition]:
monkeys[-1][True] = int(l[25:]) monkeys[-1][condition == "true"] = int(b.rsplit(" ", 1)[-1])
elif l.startswith("If f"):
monkeys[-1][False] = int(l[26:])
monkeysG = deepcopy(monkeys) p1 = monkey_business(monkeys, 20, False)
p2 = monkey_business(monkeys, 10000, True)
for it in range(20): print(f"Silver: {p1}\nGold: {p2}")
for m in monkeys:
for old in m["items"]:
m["count"] += 1
new = eval(m["op"]) // 3
monkeys[m[not (new % m["test"])]]["items"].append(new)
m["items"].clear()
ohmygodihateyoueric = prod(m["test"] for m in monkeys)
for it in range(10000):
for m in monkeysG:
for old in m["items"]:
m["count"] += 1
new = eval(m["op"]) % ohmygodihateyoueric
monkeysG[m[not (new % m["test"])]]["items"].append(new)
m["items"].clear()
resS = sorted(m["count"] for m in monkeys)[-2:]
resG = sorted(m["count"] for m in monkeysG)[-2:]
print(f"Silver: {prod(resS)}\nGold: {prod(resG)}")