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.

it got super messy, but i had fun solving this one tbh. the way i built my all_dirs list in particular is pretty hacky and scuffed, please tell me the smarter way to do it

from typing import Dict, Any

with open("day7input.txt") as f:
    input = f.read().split("\n")

class Dir:
    def __init__(self, directories: Dict[str, Any], files: Dict[str, int], origin): # directories' values are of type Dir but type hints wouldnt let me do it
        self.directories = directories
        self.files = files
        self.origin = origin

    def get_size(self):
        size = sum(self.files.values()) + sum(directory.get_size() for directory in self.directories.values())
        return size

    def enter_directory(self, name):
        return self.directories[name]

    def leave_directory(self, name):
        return self.origin

main = Dir({}, {}, None)

for line in input[2:10]:
    if line.startswith("dir"):
        _, name = line.split(" ")
        main.directories[name] = Dir({}, {}, main)
    elif line[0] in tuple("1234567890"):
        line = line.split(" ")
        size, name = int(line[0]), line[1]
        main.files[name] = size

current = main

for line in input[10:]:
    if line.startswith("dir"):
        _, name = line.split(" ")
        current.directories[name] = Dir({}, {}, current)
    elif line[0] in tuple("1234567890"):
        line = line.split(" ")
        size, name = int(line[0]), line[1]
        current.files[name] = size
    elif line.startswith("$ cd"):
        if line.split(" ")[2] == "..":
            current = current.origin
        else:
            name = line.split(" ")[2]
            current = current.directories[name]

all_dirs = [dir for dir in main.directories.values()]
for _ in range(1000):
    for dir in all_dirs:
        for sub_dir in dir.directories.values():
            if sub_dir not in all_dirs:
                all_dirs.append(sub_dir)

# part 1

answer = 0
for dir in all_dirs:
    if dir.get_size() <= 100000:
        answer += dir.get_size()

print(answer)

# part 2

main_size = main.get_size()
options: Dict[int, Dir] = {}
for dir in all_dirs:
    if main_size - dir.get_size() < 40000000:
        options[dir.get_size()] = dir
answer = options[sorted(list(options))[0]].get_size()
print(answer)
Jump in the discussion.

No email address required.

You are the first dramatard who managed to subtract 3 from 7 LMAO.

Jump in the discussion.

No email address required.

:#marseybigbrain:

Jump in the discussion.

No email address required.

Don't get too proud of yourself, if line[0] in tuple("1234567890") is unnecessary on several levels, also for _ in range(1000): is quite pointless.

Jump in the discussion.

No email address required.

if line[0] in tuple("1234567890") is unnecessary on several levels

which way is better?

for _ in range(1000): is quite pointless.

true it's r-slurred but it just werked

Jump in the discussion.

No email address required.

if line[0] in "1234567890" would work but at that point why not just force-cast the whole thing to int and see what happens?

for _ in range(1000):

I honestly don't get what it does: is it the megatard way of building subdirectory trees?

Jump in the discussion.

No email address required.

>if line[0] in "1234567890" would work

oh :marseyxd:

>I honestly don't get what it does: is it the megatard way of building subdirectory trees?

:marseyagree: it gets a layer deeper every pass. i decided to do that because i thought of it fast. unlike many other (cowardly) uses here, i dont change my code at all before posting other than adding # part 1 and # part 2. embrace the megatard within.

Jump in the discussion.

No email address required.

>tfw solve a tree problem without recursion

tardking shit my neighbor :marseykneel:

Jump in the discussion.

No email address required.

But that's a magic number! Those are bad!

Jump in the discussion.

No email address required.

hey atheists, if you don't believe in magic, how come you are afraid of magic numbers? checkmate

Jump in the discussion.

No email address required.

Have you owned the libs yet?

Jump in the discussion.

No email address required.

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