Callista Krebs

Home Projects Contact

Advent of Code - Day 1

< Advent of Code Next Day >

My Code

left = []
right = []
with open("day1.txt") as f:
    for line in f.readlines():
        line.replace("\n","")
        curr = line.split("   ")
        left.append(int(curr[0]))
        right.append(int(curr[1]))

left.sort()
right.sort()

right_count = {}
for i in range (len(right)):
    if right[i] in right_count.keys():
        right_count[right[i]] += 1
    else:
        right_count[right[i]] = 1 

score = 0
for i in range(len(left)):
    if left[i] in right_count.keys():
        score += left[i] * right_count[left[i]]
    else:
        score += left[i] * 0

print(score)

ChatGPT’s Improved Code

from collections import Counter

# Initialize lists
left = []
right = []

# Read and process the file
with open("day1.txt") as f:
    for line in f:
        # Strip newline characters and split the line into parts
        curr = line.strip().split("   ")
        # Append values to respective lists
        left.append(int(curr[0]))
        right.append(int(curr[1]))

# Sort the lists (not strictly necessary for the given logic but kept if needed elsewhere)
left.sort()
right.sort()

# Use Counter to simplify counting occurrences in the 'right' list
right_count = Counter(right)

# Calculate the score
score = sum(
    left[i] * right_count.get(left[i], 0) 
    for i in range(len(left))
)

# Print the final score
print(score)

What I Learned

strip()

collections.Counter

dict.get()

sum()


Callista Krebs, 2024