Description
Part 1 is very easy just find which values are in the ranges. Part 2 need to find the total number of all numbers within the ranges, take note there will be repeated ranges
2-5, total count is 4
Code
def combine_ranges(ranges):
ranges.sort(key=lambda x: x[0]) # Sort the ranges is important
combined = [ranges[0]] # Initialize combined list with the first range
for start, end in ranges[1:]:
# Compare the start of the current range with the end of the last combined range
# If the current range overlaps with the last combined range, merge them
if start <= combined[-1][1]:
combined[-1][1] = max(combined[-1][1], end)
else:
combined.append([start, end])
return combined
with open("input", "r") as f:
content = f.read().strip().splitlines()
ranges = [[int(x), int(y)] for x, y in map(lambda x: x.split("-"), content)]
combined_ranges = combine_ranges(ranges)
total = 0
for start, end in combined_ranges:
total += end - start + 1
print(total)