mělo to 2 části.
def parse_line(line):
reg1 = r'([a-z]+) \(([0-9]+)\)'
reg2 = r' -> ([a-z\s,]+)'
res = re.match(reg1 + reg2, line)
if res:
children = re.split(r', ', res.group(3))
else:
res = re.match(reg1, line)
children = []
return res.group(1), int(res.group(2)), children
def root(parents, children):
return list(set(parents) - set(children))[0]
def process_input(input):
return zip(*list(map(parse_line, input)))
def a_7_part1(input):
names, _, children = process_input(input)
return root(names, sum(children, []))
def catch_e(exception, func, *args):
try:
func(*args)
except exception as e:
return e.args[0]
def a_7_part2(input):
names, weights, children = process_input(input)
weights = dict(zip(names, weights))
tree = dict(zip(names, children))
def walk(node):
children = tree[node]
sums = list(map(walk, children))
counts = Counter(sums)
if len(counts) > 1:
(w1, _), (w2, _) = counts.most_common(2)
wrong_w = weights[children[sums.index(w2)]]
raise ValueError(wrong_w + w1 - w2)
return weights[node] + sum(sums)
return catch_e(ValueError, walk, root(names, sum(children, [])))
chtěl bych vidět vaše řešení.