|
@@ -0,0 +1,46 @@
|
|
1
|
+from types import SimpleNamespace
|
|
2
|
+
|
|
3
|
+programs = {}
|
|
4
|
+
|
|
5
|
+with open('data/07.txt', 'r') as file:
|
|
6
|
+ for line in file.readlines():
|
|
7
|
+ if '->' in line:
|
|
8
|
+ details, children = line.strip().split(' -> ')
|
|
9
|
+ children = children.split(', ')
|
|
10
|
+ else:
|
|
11
|
+ details = line.strip()
|
|
12
|
+ children = []
|
|
13
|
+
|
|
14
|
+ name, weight = details.split(' ')
|
|
15
|
+ weight = int(weight.strip('()'))
|
|
16
|
+ programs[name] = SimpleNamespace(name=name, weight=weight, total_weight=-1, child_names=children, children=[])
|
|
17
|
+
|
|
18
|
+roots = list(programs.keys())
|
|
19
|
+leaves = []
|
|
20
|
+
|
|
21
|
+for program in list(programs.values()):
|
|
22
|
+ for child in program.child_names:
|
|
23
|
+ program.children.append(programs[child])
|
|
24
|
+ programs[child].parent = program
|
|
25
|
+ roots.remove(child)
|
|
26
|
+ if len(program.children) == 0:
|
|
27
|
+ leaves.append(program)
|
|
28
|
+
|
|
29
|
+print(f'Part one: {programs[roots[0]].name}')
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+def resolve_weight(program):
|
|
33
|
+ if program.total_weight == -1:
|
|
34
|
+ program.total_weight = program.weight + sum(resolve_weight(child) for child in program.children)
|
|
35
|
+ return program.total_weight
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+def check_weight(program):
|
|
39
|
+ weights = [child.total_weight for child in program.children]
|
|
40
|
+ for child in program.children:
|
|
41
|
+ if weights.count(child.total_weight) == 1:
|
|
42
|
+ return check_weight(child) or next(w for w in weights if w != child.total_weight) - sum(c.total_weight for c in child.children)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+resolve_weight(programs[roots[0]])
|
|
46
|
+print(f'Part two: {check_weight(programs[roots[0]])}')
|