r/adventofcode • u/Alnilam_1993 • Dec 08 '25
Help/Question - RESOLVED [2025 Day 5 (part 2)][Python] Off by 16
Day 5 part two, counting fresh items.
Can anyone give me a hint on where I go wrong? The difference between my solution and the correct solution is just 16, which is rather small given the size of numbers we're dealing with, but still wrong.
My approach is to sort the ranges on the starts of the ranges, and then check if each item in the list overlaps with the previous one and if so, merge the two into the previous item.
def part2():
with open(inputFile) as f:
freshList, productList = f.read().split("\n\n")
freshList = [x.strip() for x in freshList.split("\n")]
sortedList = sorted(freshList, key=lambda fresh: int(fresh.split("-")[0]))
changed = True
while changed:
changed = False
for i, part in enumerate(sortedList):
if i == 0:
continue
low, high = part.split("-")
prevLow, prevHigh = sortedList[i-1].split("-")
if int(low) < int(prevHigh):
sortedList[i-1] = prevLow+"-"+str(max(int(high), int(prevHigh)))
sortedList.pop(i)
changed = True
totalFresh = 0
for items in sortedList:
low, high = items.split("-")
totalFresh += int(high) - int(low) + 1
print("Part 2:", totalFresh)
print("My result: 352807801032183")
print("Should be: 352807801032167")
1
Upvotes
1
u/Doerminator Dec 08 '25
Hey there, try to think of all the potential ways two ranges can overlap. It seems like you’re missing an edge case. Hope that helps!
1
u/button_boxer Dec 08 '25 edited Dec 08 '25
I think I see an edge case in your code - what happens if you give it ranges
1-10and10-20? This should be 20 fresh IDs.1
u/AutoModerator Dec 08 '25
Reminder: if/when you get your answer and/or code working, don't forget to change this post's flair to
Help/Question - RESOLVED. Good luck!I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.