import re GAME1 = """ Game 1: 3 blue, 4 red; 1 red, 2 green, 6 blue; 2 green Game 2: 1 blue, 2 green; 3 green, 4 blue, 1 red; 1 green, 1 blue Game 3: 8 green, 6 blue, 20 red; 5 blue, 4 red, 13 green; 5 green, 1 red Game 4: 1 green, 3 red, 6 blue; 3 green, 6 red; 3 green, 15 blue, 14 red Game 5: 6 red, 1 blue, 3 green; 2 blue, 1 red, 2 green """ """ he bag contained only 12 red cubes, 13 green cubes, and 14 blue cubes? """ MAX = { "red": 12, "green": 13, "blue": 14, } def solve(text): r = re.compile(r"(\d+) (\w+)") r2 = re.compile(r"Game (\d+):") s = 0 for line in text.splitlines(): if line.strip() == "": continue id = r2.match(line).groups()[0] m = r.findall(line) for n, c in m: if int(n) > MAX[c]: break else: s += int(id) return s def solve2(text): r = re.compile(r"(\d+) (\w+)") s = 0 for line in text.splitlines(): max = { "red": 0, "green": 0, "blue": 0, } if line.strip() == "": continue m = r.findall(line) for n, c in m: n = int(n) if n > max[c]: max[c] = int(n) s += (max["red"] * max["green"] * max["blue"]) return s if __name__ == "__main__": assert(solve(GAME1) == 8) assert(solve2(GAME1) == 2286) # 10:55 with open("i2.txt", 'r') as f: text = f.read() print(solve(text)) print(solve2(text))