-
Notifications
You must be signed in to change notification settings - Fork 0
/
part_a.py
executable file
·78 lines (66 loc) · 1.99 KB
/
part_a.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python3
import functools
import re
from dataclasses import dataclass
from typing import Dict, Set
import utils
class Challenge(utils.BaseChallenge):
def solve(self, _input, debug=False):
"""
>>> Challenge().default_solve()
113
"""
return Network.from_pipes_text(_input).get_group_size(0)
@dataclass
class Network:
groups: Dict[int, Set[int]]
re_pipe = re.compile(r'^(\d+) <-> ((?:\d+)(?:, \d+)*)$')
@classmethod
def from_pipes_text(cls, pipes_text):
groups = {}
for line in pipes_text.strip().splitlines():
main_str, pipes_str = cls.re_pipe.match(line).groups()
main = int(main_str)
pipes = set(map(int, pipes_str.split(', ')))
programs = pipes | {main}
programs_groups = [
groups[program]
for program in programs
if program in groups
] + [programs]
group = functools.reduce(set.__or__, programs_groups)
groups.update({
program: group
for program in group
})
return cls(groups)
def get_group_size(self, program):
"""
>>> Network.from_pipes_text(
... "0 <-> 2\\n"
... "1 <-> 1\\n"
... "2 <-> 0, 3, 4\\n"
... "3 <-> 2, 4\\n"
... "4 <-> 2, 3, 6\\n"
... "5 <-> 6\\n"
... "6 <-> 4, 5\\n"
... ).get_group_size(0)
6
"""
return len(self.get_group(program))
def get_group(self, program):
"""
>>> sorted(Network.from_pipes_text(
... "0 <-> 2\\n"
... "1 <-> 1\\n"
... "2 <-> 0, 3, 4\\n"
... "3 <-> 2, 4\\n"
... "4 <-> 2, 3, 6\\n"
... "5 <-> 6\\n"
... "6 <-> 4, 5\\n"
... ).get_group(0))
[0, 2, 3, 4, 5, 6]
"""
return self.groups[program]
Challenge.main()
challenge = Challenge()