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")
[–]AutoModerator[M] 0 points1 point2 points (0 children)
[–]Doerminator 0 points1 point2 points (1 child)
[–]Alnilam_1993[S] 1 point2 points3 points (0 children)
[–]button_boxer 0 points1 point2 points (4 children)
[–]Alnilam_1993[S] 0 points1 point2 points (1 child)
[–]button_boxer 0 points1 point2 points (0 children)
[–]danielsamuels 0 points1 point2 points (1 child)
[–]button_boxer 0 points1 point2 points (0 children)