Callista Krebs

Home Projects Contact

Advent of Code - Day 3

< Prev Day Next Day >

My Code

import re

with open("day3.txt") as f:
    instructions = f.read()
    multipliers = re.findall("mul\\(\\d\\d?\\d?,\\d\\d?\\d?\\)", instructions)
    
    sum = 0
    for item in multipliers:
        nums = list(map(int,item.strip("mul()").split(",")))
        sum += nums[0] * nums[1]

print(sum)

ChatGPT’s Improved Code

import re

# Open the file using a context manager and read its content
with open("day3.txt", "r") as file:
    instructions = file.read()

# Use a more descriptive variable name for the matches
pattern = r"mul\((\d{1,3}),(\d{1,3})\)"
matches = re.findall(pattern, instructions)

# Calculate the sum in a more Pythonic way using a generator expression
total_sum = sum(int(a) * int(b) for a, b in matches)

# Print the result
print(total_sum)

What I Learned

Regex review

Capturing Groups in regex

Better Syntax


Callista Krebs, 2024