with open('puzzle.txt', 'r') as f: lines = f.read().splitlines() import re total_mul = 0 doing = True for line in lines: match = re.findall(r"mul\([0-9]+,[0-9]+\)|do\(\)|don't\(\)", line) for instruction in match: print(instruction) if instruction == "do()": doing = True elif instruction == "don't()": doing = False elif instruction.startswith("mul"): if doing: x, y = map(int, instruction.strip('mul()').split(',')) total_mul += x * y print(total_mul)