Advent of Code 2024 - Day 3

# Part 1

 1import re
 2
 3def get_data():
 4    with open("day_3_input.txt") as f:
 5        return f.read().strip()
 6
 7def get_mults(data):
 8    regex = r"mul\((\d+),(\d+)\)"
 9    for match in re.finditer(regex, data):
10        yield [int(match[0]), int(match[1])]
11
12def main(data):
13    output = 0
14    for x, y in get_mults(data):
15        output += x * y
16    return output
17
18if __name__ == "__main__":
19    print(f"{main(get_data()) = }")

# Part 2

 1import re
 2
 3def get_data():
 4    with open("day_3_input.txt") as f:
 5        return f.read().strip()
 6
 7def get_mults(data):
 8    regex = r"mul\((\d+),(\d+)\)|do\(\)|don't\(\)"
 9    enabled = True
10    for m in re.finditer(regex, data):
11        match m.group(0):
12            case "do()":
13                enabled = True
14            case "don't()":
15                enabled = False
16            case _:
17                if enabled:
18                    yield [int(m.group(1)), int(m.group(2))]
19
20def main(data):
21    output = 0
22    for x, y in get_mults(data):
23        output += x * y
24    return output
25
26if __name__ == "__main__":
27    print(f"{main(get_data()) = }")