Solution for problem 8 in Python

This commit is contained in:
David Doblas Jiménez 2022-04-08 16:25:18 +02:00
parent 9c8c2677e2
commit 6b33d543e8
1 changed files with 54 additions and 1 deletions

View File

@ -47,6 +47,7 @@
# What is the sum of all metadata entries?
from copy import copy
from typing import List
with open("files/P8.txt") as f:
@ -65,8 +66,60 @@ def sum_metadata(lst: List[int]) -> int:
def part_1() -> None:
print(f"The sum of all metadata entries is {sum_metadata(tree)}")
tree_p1 = copy(tree)
print(f"The sum of all metadata entries is {sum_metadata(tree_p1)}")
# --- Part Two ---
# The second check is slightly more complicated: you need to find the value of
# the root node (A in the example above).
# The value of a node depends on whether it has child nodes.
# If a node has no child nodes, its value is the sum of its metadata entries.
# So, the value of node B is 10+11+12=33, and the value of node D is 99.
# However, if a node does have child nodes, the metadata entries become indexes
# which refer to those child nodes. A metadata entry of 1 refers to the first
# child node, 2 to the second, 3 to the third, and so on. The value of this
# node is the sum of the values of the child nodes referenced by the metadata
# entries. If a referenced child node does not exist, that reference is
# skipped. A child node can be referenced multiple time and counts each time it
# is referenced. A metadata entry of 0 does not refer to any child node.
# For example, again using the above nodes:
# Node C has one metadata entry, 2. Because node C has only one child node,
# 2 references a child node which does not exist, and so the value of node C is
# 0.
# Node A has three metadata entries: 1, 1, and 2. The 1 references node A's
# first child node, B, and the 2 references node A's second child node, C.
# Because node B has a value of 33 and node C has a value of 0, the value of
# node A is 33+33+0=66.
# So, in this example, the value of the root node is 66.
# What is the value of the root node?
def find_root_value(lst: List[int]) -> int:
childs = lst.pop(0)
metadata = lst.pop(0)
values = [find_root_value(lst) for _ in range(childs)]
metadatas = [lst.pop(0) for _ in range(metadata)]
if childs == 0:
return sum(metadatas)
return sum(
values[child - 1] for child in metadatas if child - 1 in range(childs)
)
def part_2() -> None:
tree_p2 = copy(tree)
print(f"The value of the root node is {find_root_value(tree_p2)}")
if __name__ == "__main__":
part_1()
part_2()