Ahí va la mía, un tanto in extremis. Hoy no me he podido poner hasta hace un rato y cuando he visto el enunciado (el típico problema de árboles del AoC) he estado a punto de no hacerlo. Pero al final me he animado. No estoy nada orgulloso de la solución, la verdad, creo que es una implementación bastante mala de un árbol.
with open("input7.txt") as f:
inp = f.read().splitlines()
inp = [x.split() for x in inp]
class Tree:
def __init__(self, name, parent, values, children, size = None):
self.name = name
self.parent = parent
self.values = values
self.children = children
self.size = size
def update_child(self, child):
self.children.append(child)
def update_values(self, value):
self.values.append(value)
def update_size(self, size):
self.size = size
def get_name(self):
return self.name
def get_parent(self):
return self.parent
def get_children(self):
return self.children
def get_values(self):
return self.values
def get_size(self):
return self.size
def create_file_tree(instructions):
file_tree = Tree(None, None, [], [])
current = file_tree
for inst in instructions:
if inst[0] == '$' and inst[1] == 'cd':
if inst[2] == "..":
current = current.get_parent()
else:
new = Tree(name = inst[2], parent = current, children = [], values = [])
current.update_child(new)
current = new
elif inst[0][0] in '123456789':
current.update_values((int(inst[0]), inst[1]))
return file_tree
file_tree = create_file_tree(inp)
file_tree = file_tree.get_children()[0]
# Part 1
def compute_size(file_tree):
if not file_tree.get_children():
file_tree.update_size(sum([x for (x, _) in file_tree.get_values()]))
else:
new_size = sum([x for (x, _) in file_tree.get_values()]) + sum([compute_size(x).get_size() for x in file_tree.get_children()])
file_tree.update_size(new_size)
return file_tree
file_tree = compute_size(file_tree)
def get_sizes(file_tree):
if not file_tree.get_children():
size = file_tree.get_size()
return [size]
return [file_tree.get_size()] + [y for x in file_tree.get_children() for y in get_sizes(x)]
print(sum([x for x in get_sizes(file_tree) if x<=100000]))
# Part 2
unused = 70000000 - file_tree.get_size()
print(min([x for x in get_sizes(file_tree) if x+unused >= 30000000]))