I was very late to the (Christmas) party, discovering Advent of Code just this year.
It was proving quite fun until I got stuck on Day 5 Part 2.
The challenge (as I understand it) is to take this input (a list of integer ranges) and return the total number of unique integers which appear within it.
My approach was to sort the list by first number in range and then by second number, then merge all overlapping ranges so that all ranges within the list are distinct. Finally I iterate the list again and tot up the number of integers in each range to reach a final total value.
My code works on the sample code but apparently not on the much larger input above.
EDIT: This code does not work on the sample code (earlier iterations did).
def total_fresh_ids(ranges):
total=0
for i,_ in enumerate(ranges):
ranges[i] = ranges[i].split('-')
ranges.sort(key=lambda r: (int(r[0]), int(r[1])))
#print(ranges)
for i,x in enumerate(ranges):
if i<len(ranges)-1:
if int(x[1])>=int(ranges[i+1][0]):
#print("merge", x, ranges[i+1])
#merge with next
ranges[i+1][0] = x[0]
#print("merged", ranges[i+1])
del ranges[i]
#else:
#print("no merge", x)
for z in ranges:
total += int(z[1])-int(z[0]) + 1
#print(total)
return ("total:", total)
print(total_fresh_ids(ranges))
# output: ('total:', 346024201522906)
I converted the above input into a list in this format (before executing the above code) :
ranges = [ '70642195371793-72879218404633',
'173870324743912-174003164605263',
'201707880905704-210661896929678',
'506861791312713-507300657398991',
'323726482687518-323726482687518',
'450429140158342-450429140158342',
'81503580676246-81736399903236'
... etc ...
'503254477307191-504094553585169',
'367570185836554-369643343702845',
'507300657398991-507790184520273',
'264221915693854-268980593812546' ]
Can anyone help me understand what I’m doing wrong please?