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
from copy import deepcopy
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 = []
for l in sys.stdin:
l = l.strip()
if l.startswith("M"):
monkeys.append({})
monkeys[-1]["count"] = 0
elif l.startswith("S"):
monkeys[-1]["items"] = [int(x) for x in l[16:].split(", ")]
elif l.startswith("O"):
monkeys[-1]["op"] = l[17:]
elif l.startswith("T"):
monkeys[-1]["test"] = int(l[19:])
elif l.startswith("If t"):
monkeys[-1][True] = int(l[25:])
elif l.startswith("If f"):
monkeys[-1][False] = int(l[26:])
for a, b in [l.strip().split(":") for l in sys.stdin if ":" in l]:
match a.split():
case ["Monkey", _]:
monkeys.append({})
monkeys[-1]["count"] = 0
case ["Starting", "items"]:
monkeys[-1]["items"] = [int(x) for x in b.split(", ")]
case ["Operation"]:
monkeys[-1]["op"] = op2func(b.split(" = ")[1])
case ["Test"]:
monkeys[-1]["test"] = int(b.rsplit(" ", 1)[-1])
case ["If", condition]:
monkeys[-1][condition == "true"] = int(b.rsplit(" ", 1)[-1])
monkeysG = deepcopy(monkeys)
for it in range(20):
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)}")
p1 = monkey_business(monkeys, 20, False)
p2 = monkey_business(monkeys, 10000, True)
print(f"Silver: {p1}\nGold: {p2}")