adventofcode2022/day04/day04.py

48 lines
1.2 KiB
Python

#!/usr/bin/env python3
import re
assignment_pairs = [
"2-4,6-8",
"2-3,4-5",
"5-7,7-9",
"2-8,3-7",
"6-6,4-6",
"2-6,4-8"]
def pair_issubset(pair):
a, b, c, d = map(int, re.split('\-|\,', pair))
section1 = set(range(a, b+1)).issubset(set(range(c, d+1)))
section2 = set(range(c, d+1)).issubset(set(range(a, b+1)))
return section1 or section2
def pair_notdisjoint(pair):
a, b, c, d = map(int, re.split('\-|\,', pair))
return not set(range(a, b+1)).isdisjoint(set(range(c, d+1)))
if __name__ == "__main__":
sum_fully_contain = 0
sum_overlap = 0
for pair in assignment_pairs:
if pair_issubset(pair):
sum_fully_contain += 1
if pair_notdisjoint(pair):
sum_overlap += 1
print("Part 1 test: %s" % sum_fully_contain)
print("Part 2 test: %s" % sum_overlap)
file = open("input","r")
lines = file.read().splitlines()
sum_fully_contain = 0
sum_overlap = 0
for pair in lines:
if pair_issubset(pair):
sum_fully_contain += 1
if pair_notdisjoint(pair):
sum_overlap += 1
print("Part 1: %s" % sum_fully_contain)
print("Part 2: %s" % sum_overlap)