Advertisement
Guest User

Untitled

a guest
Dec 4th, 2022
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. from typing import Iterable, List
  2. import pathlib
  3.  
  4.  
  5. def read_data():
  6.     with open(f"data/{pathlib.Path(__file__).stem}.txt") as raw_data:
  7.         return raw_data.readlines()
  8.  
  9.  
  10. def produce_ranges(line: str) -> Iterable[Iterable[int]]:
  11.     """ Produces two ranges from the string 'a1-a2,b1-b2' """
  12.     return [[int(r) for r in part.split('-')] for part in line.split(',')]
  13.  
  14.  
  15. def sign(x: int) -> int:
  16.     return -1 if x < 0 else 0 if x == 0 else 1
  17.  
  18.  
  19. def contained(range1: List[int], range2: List[int]) -> bool:
  20.     """ Checks if either range is contained by the other, where endpoints can be equal """
  21.     return abs(sign(range1[0]-range2[0]) + sign(range1[1]-range2[1])) <= 1
  22.  
  23.  
  24. def overlaps(range1: List[int], range2: List[int]) -> bool:
  25.     """ Checks if the ranges overlap, including if endpoints are equal """
  26.     return abs(sign(range1[0]-range2[1]) + sign(range1[1]-range2[0])) <= 1
  27.  
  28.  
  29. def part1(data: Iterable[str]) -> int:
  30.     contained_ranges = 0
  31.     for line in data:
  32.         contained_ranges += 1 if contained(*produce_ranges(line)) else 0
  33.  
  34.     return contained_ranges
  35.  
  36.  
  37. def part2(data: Iterable[str]) -> int:
  38.     overlap_ranges = 0
  39.     for line in data:
  40.         overlap_ranges += 1 if overlaps(*produce_ranges(line)) else 0
  41.  
  42.     return overlap_ranges
  43.  
  44.  
  45. def main():
  46.     data = read_data()
  47.     print(f"Part 1: {part1(data)}")
  48.     print(f"Part 2: {part2(data)}")
  49.  
  50.  
  51. if __name__ == "__main__":
  52.     main()
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement