This was way messier in the Jupyter Notebook I was playing around in and I basically just tidied it up and put both tasks in one file. Next time I'll probably read input from a file instead of just hardcoding it into an unseen variable out of laziness.
def parseinput():
input = rawinput.splitlines()
games = []
for i in input:
gamedata = []
gameid, allrounds = i.split(": ")
gameid = int(gameid.removeprefix("Game "))
allrounds = allrounds.split("; ")
rounds = []
for r in allrounds:
throws = r.split(", ")
rounds.append(throws)
gamedata = dict(id=gameid, rounds=rounds)
games.append(gamedata)
return games
def valid_game(game, cubes):
possible = True
for round in game["rounds"]:
for throw in round:
number, colour = throw.split(" ")
number = int(number)
if cubes[colour] < number:
possible = False
break
if not possible:
break
return possible
def cube_score(game):
red = 0
blue = 0
green = 0
for round in game["rounds"]:
for throw in round:
number, colour = throw.split(" ")
number = int(number)
if colour == "red":
if number > red:
red = number
elif colour == "blue":
if number > blue:
blue = number
elif colour == "green":
if number > green:
green = number
return red * blue * green
def main():
games = parseinput()
cubes = {"red": 12, "green": 13, "blue": 14}
answer1 = 0
answer2 = 0
for g in games:
if valid_game(g, cubes):
answer1 += g["id"]
answer2 += cube_score(g)
print(answer1)
print(answer2)
if __name__ == "__main__":
main()syntax highlighting by codehost