Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from typing import Iterable, List
- import pathlib
- def read_data():
- with open(f"data/{pathlib.Path(__file__).stem}.txt") as raw_data:
- return raw_data.readlines()
- def produce_ranges(line: str) -> Iterable[Iterable[int]]:
- """ Produces two ranges from the string 'a1-a2,b1-b2' """
- return [[int(r) for r in part.split('-')] for part in line.split(',')]
- def sign(x: int) -> int:
- return -1 if x < 0 else 0 if x == 0 else 1
- def contained(range1: List[int], range2: List[int]) -> bool:
- """ Checks if either range is contained by the other, where endpoints can be equal """
- return abs(sign(range1[0]-range2[0]) + sign(range1[1]-range2[1])) <= 1
- def overlaps(range1: List[int], range2: List[int]) -> bool:
- """ Checks if the ranges overlap, including if endpoints are equal """
- return abs(sign(range1[0]-range2[1]) + sign(range1[1]-range2[0])) <= 1
- def part1(data: Iterable[str]) -> int:
- contained_ranges = 0
- for line in data:
- contained_ranges += 1 if contained(*produce_ranges(line)) else 0
- return contained_ranges
- def part2(data: Iterable[str]) -> int:
- overlap_ranges = 0
- for line in data:
- overlap_ranges += 1 if overlaps(*produce_ranges(line)) else 0
- return overlap_ranges
- def main():
- data = read_data()
- print(f"Part 1: {part1(data)}")
- print(f"Part 2: {part2(data)}")
- if __name__ == "__main__":
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement