Unable to load image

Advent of Code 2022: Day 7

https://adventofcode.com
with open('AdventOfCode2022/input.txt', 'r') as input:
    commands = input.read().split('\n')

    def new_dict(name, parent=None):
        return {
        'name': name,
        'parent':parent,
        'files': 0,
        'dirs': {}
    }

    root_dict = new_dict(name='/', parent=None)
    curr_dict = root_dict

    #Build tree of dicts
    for i in range(len(commands)):
        command_parts = commands[i].split(' ')
        if command_parts[0] == '$':
            if command_parts[1] == 'cd':
                if command_parts[2] == '..':
                    curr_dict = curr_dict['parent']
                elif command_parts[2] == '/':
                    pass
                else:
                    curr_dict = curr_dict['dirs'][command_parts[2]]
        elif command_parts[0] == 'dir':
            if command_parts[1] not in curr_dict:
                curr_dict['dirs'][command_parts[1]] = new_dict(name=command_parts[1], parent=curr_dict)
        elif command_parts[0] == '':
            pass
        else:
            curr_dict['files'] += int(command_parts[0])

    #PART ONE

    MAX_THRESHOLD = 100000
    FINAL_COUNTER = 0
    dict_list = []
    
    def parse_dict(t_dict):
        folder_total = t_dict['files']

        for c_dict in t_dict['dirs'].keys():
            folder_total += parse_dict(t_dict['dirs'][c_dict])

        global dict_list
        dict_list.append(folder_total)

        if folder_total < MAX_THRESHOLD:
            global FINAL_COUNTER # this is the most embarrassing thing I've ever done
            FINAL_COUNTER += folder_total
        return folder_total

    total_used = parse_dict(root_dict)
    print(FINAL_COUNTER)

    #PART TWO
    TOTAL_SPACE = 70000000
    WANTED_SPACE = 30000000
    curr_wanted = WANTED_SPACE - (TOTAL_SPACE - total_used)
    
    larger_than_wanted = []
    for i in dict_list:
        if i > curr_wanted:
            larger_than_wanted.append(i)

    print(min(larger_than_wanted))
32
Jump in the discussion.

No email address required.

I got the recursive functions to one line of barely legible python :marseywholesome:

lines = []
with open("7.input", "r") as f:
    lines = f.readlines()

lines = [i.strip() for i in lines]

class Directory:
    def __init__(self, parent) -> None:
        self.parent = parent
        self.directories = dict()
        self.direct_size = 0
    
    def add_directory(self, name) -> None:
        self.directories[name] = Directory(self)
    
    def add_to_size(self, size) -> None:
        self.direct_size += size
    
    def get_directory(self, name) -> 'Directory':
        return self.directories[name]
    
    def get_parent(self) -> 'Directory':
        return self.parent

root = Directory(None)
current = None
for line in lines:
    args = line.split(" ")
    if args[0] == "$":
        if args[1] == "cd": 
            if "/" in line: current = root
            elif ".." in line: current = current.get_parent()
            else: current = current.get_directory(args[2])
    else:
        if args[0] == "dir": current.add_directory(args[1])
        else: current.add_to_size(int(args[0]))
    
def get_total_size(start): return sum([start.direct_size] + [get_total_size(i) for i in start.directories.values()])

def find_small_directories(start): return list(filter(None, sum([find_small_directories(i) for i in start.directories.values()], []))) + ([start] if get_total_size(start) < 100000 else [])

def get_closest_directory_to_size(start, size): return min([get_closest_directory_to_size(directory, size) for directory in start.directories.values() if get_total_size(directory) > size] + ([get_total_size(start)] if get_total_size(start) > size else []))

def solve_part_1(root) : return sum([get_total_size(i) for i in find_small_directories(root)])

part_1 = sum([get_total_size(i) for i in find_small_directories(root)])
part_2 = get_closest_directory_to_size(root, 30000000 - (70000000 - get_total_size(root)))

assert part_1 == 1141028
assert part_2 == 8278005
Jump in the discussion.

No email address required.

Some people are able to display their intelligence by going on at length on a subject and never actually saying anything. This ability is most common in trades such as politics, public relations, and law. You have impressed me by being able to best them all, while still coming off as an absolute idiot.

Jump in the discussion.

No email address required.

Link copied to clipboard
Action successful!
Error, please refresh the page and try again.