Created
December 7, 2022 15:54
-
-
Save qoda/0de28c6d9f10f72ba02a4f9a25a70eb4 to your computer and use it in GitHub Desktop.
Day 7
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
MAX_DIR_SIZE = 100_000 | |
REQUIRED_SPACE = 0 | |
def calculate_deletable(file_system): | |
total = 0 | |
for v in file_system.values(): | |
if isinstance(v, int): | |
total += v if v <= MAX_DIR_SIZE else 0 | |
if isinstance(v, dict): | |
total += calculate_deletable(v) | |
return total | |
def find_deletable(file_system): | |
deletable = [] | |
for v in file_system.values(): | |
if isinstance(v, int): | |
if v >= REQUIRED_SPACE: | |
deletable.append(v) | |
if isinstance(v, dict): | |
item = find_deletable(v) | |
if item: | |
deletable += item | |
return deletable | |
def get_dir(file_system, parents): | |
directory = file_system | |
for parent in parents: | |
directory = directory[parent] | |
return directory | |
def build_filesystem(commands, file_system=None, parents=None): | |
file_system = file_system or {'size': 0} | |
if not len(commands): | |
return file_system | |
command = commands.pop(0) | |
if command[0].startswith('cd'): | |
input = command[0].split()[1] | |
if input == '/': | |
return build_filesystem(commands, file_system, parents=[]) | |
elif input == '..': | |
parents.pop() | |
return build_filesystem(commands, file_system, parents=parents) | |
else: | |
parents.append(input) | |
return build_filesystem(commands, file_system, parents=parents) | |
elif command[0].startswith('ls'): | |
output = command[1:] | |
current_dir = get_dir(file_system, parents) | |
parent_dir = get_dir(file_system, parents[:-1]) | |
for item in output: | |
if item.startswith('dir'): | |
key = item.split()[1] | |
current_dir.update({key: {'size': 0}}) | |
else: | |
value, key = item.split() | |
if 'size' in current_dir: | |
current_dir['size'] += int(value) | |
else: | |
current_dir['size'] = int(value) | |
for count, _ in enumerate(parents): | |
parent_dir = get_dir(file_system, parents[:-count]) | |
if parent_dir != current_dir: | |
parent_dir['size'] += int(value) | |
return build_filesystem(commands, file_system, parents=parents) | |
def get_command_line(input): | |
return [[x.strip() for x in i.splitlines()] for i in input.split('$') if i and i != '\n'] | |
with open('data/day7.txt') as _file: | |
commands = get_command_line(_file.read()) | |
file_system = build_filesystem(commands) | |
# Part 1 | |
total = calculate_deletable(file_system) | |
print('Part 1:', total) | |
assert total == 1844187 | |
# Part 2 - ERROR | |
deletable_dirs = find_deletable(file_system) | |
print('Part 2:', min(deletable_dirs)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment