84 lines
1.6 KiB
Python
84 lines
1.6 KiB
Python
#!/usr/bin/env python3
|
|
|
|
from typing import TextIO
|
|
|
|
p = {"red": 12, "green": 13, "blue": 14}
|
|
|
|
p2 = []
|
|
|
|
|
|
def part1(f: TextIO) -> int:
|
|
games: int = 0
|
|
|
|
for line in f:
|
|
line = line.strip()
|
|
|
|
id_ = int(line.split(":")[0].split()[1])
|
|
|
|
line = line.split("; ")
|
|
line[0] = line[0].split(": ")[1] # remove the Game #:
|
|
clues = []
|
|
|
|
f_p2 = [] # for part 2
|
|
|
|
for c in range(len(line)):
|
|
clues.append(line[c].split(", "))
|
|
f_p2.append(clues[-1])
|
|
|
|
p2.append(f_p2)
|
|
|
|
flag = True
|
|
|
|
for peek in clues:
|
|
# for each, if type is over
|
|
# set to false, exit early and do not add the game id
|
|
for t in peek:
|
|
t = t.split()
|
|
t[0] = int(t[0])
|
|
|
|
if t[0] > p[t[1]]:
|
|
flag = False
|
|
break
|
|
|
|
if flag is False:
|
|
break
|
|
|
|
if flag is True:
|
|
games += id_
|
|
|
|
return games
|
|
|
|
|
|
def mult(p: list) -> int:
|
|
pr = 1
|
|
for item in p:
|
|
pr *= item
|
|
return pr
|
|
|
|
|
|
def part2(games: list) -> int:
|
|
sum_ = 0
|
|
|
|
for game in games:
|
|
mins: dict[str, int] = {}
|
|
|
|
for clues in game:
|
|
for clue in clues:
|
|
clue = clue.split()
|
|
clue[0] = int(clue[0])
|
|
|
|
if clue[1] in mins:
|
|
mins[clue[1]] = max(mins[clue[1]], clue[0])
|
|
else:
|
|
mins[clue[1]] = clue[0]
|
|
|
|
sum_ += mult(list(mins.values()))
|
|
|
|
return sum_
|
|
|
|
|
|
if __name__ == "__main__":
|
|
with open("day02.txt") as f:
|
|
print(part1(f))
|
|
print(part2(p2))
|