-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday07.py
More file actions
94 lines (74 loc) · 2.49 KB
/
day07.py
File metadata and controls
94 lines (74 loc) · 2.49 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import re
def calc_a(input):
ancestors = set()
rows = input.split('\n')
# collect all ancestors
for row in rows:
if '->' in row:
children = row.split('->')[1].split()
for child in children:
ancestors.add(child.replace(',', ''))
# get node that's not an ancestor
for row in rows:
node = row.split()[0]
if node not in ancestors:
return node
return "not found "
def calc_b(input):
nodes = {}
weight_patter = re.compile(".*\((\d+)\).*")
rows = input.split('\n')
# create all nodes
for row in rows:
name = row.split()[0]
m = weight_patter.match(row)
weight = int(m.group(1), 10)
node = Node(weight, name)
nodes[name] = node
# build graph (connect all children)
for row in rows:
if '->' in row:
name = row.split()[0]
node = nodes[name]
children = row.split('->')[1].split()
for child in children:
child_name = child.replace(',', '')
child_node = nodes[child_name]
node.add_child(child_node)
parent_name = calc_a(input)
parent_node = nodes[parent_name]
return parent_node.find_imbalance()
class Node:
def __init__(self, weight, name):
self.weight = weight
self.name = name
self.children = []
def add_child(self, node):
self.children.append(node)
def get_weight(self):
child_weights = 0
for child in self.children:
child_weights += child.get_weight()
return self.weight + child_weights
def has_imbalanced_children(self):
if len(self.children) == 0:
return False
weight = self.children[0].get_weight()
for child in self.children:
if child.get_weight() != weight:
return True
return False
def find_imbalance(self):
# seems like there's always an overweight rather than underweight
max = 0
min = 999999999
for child in self.children:
# print(child.name, child.get_weight(), child.weight)
if child.get_weight() < min:
min = child.get_weight()
if child.get_weight() > max:
max = child.get_weight()
unbalanced_node = child
if unbalanced_node.has_imbalanced_children():
return unbalanced_node.find_imbalance()
return unbalanced_node.weight - (max - min)