import re pattern = re.compile('mul\\(([0-9]{1,3}),([0-9]{1,3})\\)') do_pattern = re.compile('do\\(\\)') dont_pattern = re.compile("don't\\(\\)") with open("input") as f: data = f.read() do_dont_intervals = [] for match in do_pattern.finditer(data): do_dont_intervals.append((match.start(), True)) for match in dont_pattern.finditer(data): do_dont_intervals.append((match.start(), False)) do_dont_intervals.sort(key=lambda elem: elem[0]) def get_do_state(intervals: list[tuple[int, bool]], pos: int): current_state = True for elem in intervals: if elem[0] > pos: break else: current_state = elem[1] return current_state result = 0 for match in pattern.finditer(data): if get_do_state(do_dont_intervals, match.start()): result += int(match.group(1)) * int(match.group(2)) print(result)