47 lines
949 B
Python
47 lines
949 B
Python
with open('data/08.txt') as f:
|
|
data = [int(n) for n in f.read().split()]
|
|
|
|
|
|
all_meta = []
|
|
|
|
def parse(data):
|
|
(children, meta_count), data = data[:2], data[2:]
|
|
tree = {
|
|
'children': [],
|
|
'metadata': []
|
|
}
|
|
|
|
for i in range(children):
|
|
child, data = parse(data)
|
|
tree['children'].append(child)
|
|
|
|
for i in range(meta_count):
|
|
m = data.pop(0)
|
|
all_meta.append(m)
|
|
tree['metadata'].append(m)
|
|
|
|
return tree, data
|
|
|
|
|
|
tree, _ = parse(data)
|
|
|
|
print(f'Part 1: {sum(all_meta)}\n')
|
|
|
|
|
|
def value(node):
|
|
children, metadata, = node['children'], node['metadata']
|
|
if len(children) == 0:
|
|
return sum(metadata)
|
|
|
|
child_values = []
|
|
for i in metadata:
|
|
if i == 0:
|
|
continue
|
|
try:
|
|
child_values.append(value(children[i - 1]))
|
|
except IndexError:
|
|
pass
|
|
return sum(child_values)
|
|
|
|
print(f'Part 2: {value(tree)}\n')
|