adventofcode/2023/day2/main.py
2023-12-02 15:10:31 +01:00

49 lines
1.4 KiB
Python

from math import prod
import re
def part1(file: str):
acc = []
with open(file) as f:
for idx, line in enumerate(f, start=1):
game = {"red": 12, "green": 13, "blue": 14} # limits
try:
for match in re.finditer(
"|".join([rf"(?P<{k}>\d+(?= {k}))" for k in game.keys()]), line
):
for k in game.keys():
if match.group(k):
if int(match.group(k)) > game[k]:
raise Exception
except Exception:
pass
else:
acc.append(idx)
return sum(acc)
def part2(file: str):
acc = []
with open(file) as f:
for line in f:
game = {"red": 0, "green": 0, "blue": 0}
for match in re.finditer(
"|".join([rf"(?P<{k}>\d+(?= {k}))" for k in game.keys()]), line
):
for k in game.keys():
if match.group(k):
value = int(match.group(k))
if value > game[k]:
game[k] = value
acc.append(prod(game.values()))
return sum(acc)
if __name__ == "__main__":
assert part1("example.txt") == 8
print(part1("input.txt"))
assert part2("example.txt") == 2286
print(part2("input.txt"))