with open('data-2022-04.txt', 'r') as f:
inp = f.read().splitlines()Advent of Code 2022 Day 4
— Day 4: Camp Cleanup —
The elves need to do some cleaning, and have been assigned sections of the camp.
In how many assignment pairs does one range fully contain the other?
There is some preparation required
task1 = [x.split(',') for x in inp]
task2 = [x[0].split('-') + x[1].split('-') for x in task1]
task3 = [list(map(int, x)) for x in task2]Now, do we have any overlapping ranges? Probably.
def within(lst):
# first pair within second
if lst[0] >= lst[2] and lst[1] <= lst[3]:
return True
# second pair within first
elif lst[2] >= lst[0] and lst[3] <= lst[1]:
return True
else:
return FalseSweet, let’s check the list
num1 = [within(x) for x in task3]
sum(num1)
# 571571
— Part Two —
Actually, we’re just looking for any overlap, rather than one within the other.
In how many assignment pairs do the ranges overlap?
def overlap(lst):
return lst[1] < lst[2] or lst[3] < lst[0]And use this on our list
num2 = [overlap(x) for x in task3]
1000 - sum(num2)
# 917917