Passed
Push — main ( 83fd9b...e71399 )
by Yohann
57s
created

main.LinearRange.is_overlapping()   A

Complexity

Conditions 1

Size

Total Lines 5
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 5
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nop 2
1
from __future__ import annotations
2
3
import pathlib
4
from typing import List, Tuple, cast
5
6
7
class LinearRange:
8
9
    def __init__(self, start, stop):
10
        self.start = start
11
        self.stop = stop
12
13
    def is_subset_of(self, other: LinearRange) -> bool:
14
        return self.start <= other.start and self.stop >= other.stop
15
16
    def is_overlapping(self, other: LinearRange) -> bool:
17
        return (
18
            self.start <= other.start <= self.stop
19
            or self.start <= other.stop <= self.stop
20
            or other.start <= self.start <= other.stop
21
        )
22
23
    @classmethod
24
    def from_string(cls, string: str) -> LinearRange:
25
        start, stop = map(int, string.split('-'))
26
        return cls(start, stop)
27
28
    def __repr__(self):
29
        return f'<{self.start} -> {self.stop}>'
30
31
32
def retrieve_groups(lines: List[str]) -> List[Tuple[LinearRange, LinearRange]]:
33
    return cast(
34
        List[Tuple[LinearRange, LinearRange]],
35
        [
36
            tuple(map(LinearRange.from_string, line.split(',')))
37
            for line in lines if line.count(',') == 1
38
        ]
39
    )
40
41
42
def count_checked_group(group, func):
43
    return sum(func(left, right) or func(right, left) for left, right in group)
44
45
46
def main():
47
    content = pathlib.Path('./input.txt').read_text()
48
    groups = retrieve_groups(content.splitlines())
49
50
    print("Part 1:", count_checked_group(groups, LinearRange.is_subset_of))
51
    print("Part 2:", count_checked_group(groups, LinearRange.is_overlapping))
52
53
54
if __name__ == '__main__':
55
    main()
56