#!/usr/bin/env python3.8 """ Within the terminal output, lines that begin with $ are commands you executed, very much like some modern computers: cd means change directory. This changes which directory is the current directory, but the specific result depends on the argument: cd x moves in one level: it looks in the current directory for the directory named x and makes it the current directory. cd .. moves out one level: it finds the directory that contains the current directory, then makes that directory the current directory. cd / switches the current directory to the outermost directory, /. ls means list. It prints out all of the files and directories immediately contained by the current directory: 123 abc means that the current directory contains a file named abc with size 123. dir xyz means that the current directory contains a directory named xyz. """ import sys from pathlib import Path import pytest import time from functools import wraps INPUTS_DIR = 'inputs' INPUT_FILE = 'day07.txt' PROJECT_DIR = Path('.') FILE_PATH = PROJECT_DIR / INPUTS_DIR / INPUT_FILE LOOP_NO = 1 def f_time(f): @wraps(f) def time_check(*args, **kwargs): print(f'{LOOP_NO=}') start_time = time.monotonic() for i in range(LOOP_NO): sizes = f(*args, *kwargs) end_time = time.monotonic() print(f"It took {end_time-start_time:.10f} seconds to compute") return sizes return time_check FACTOR_SIZE = 10**5 DISK_SPACE = 7*10**7 UNUSED_SPACE = 3*10**7 def read_filesystem_output(file_path): with open(file_path) as f: return f.read() @f_time def filesystem_directory_structure_size(file_path, output=None): output = output or read_filesystem_output(file_path) output = output.strip().split('\n') fs = create_filesystem_struct(output) calc_dir_1kk = calculate_directory_limited_size(fs, limit=FACTOR_SIZE) return calc_dir_1kk @f_time def filesystem_directory_tree_size(file_path, output=None): output = output or read_filesystem_output(file_path) output = output.strip().split('\n') fs = create_filesystem_tree(output) total_size, limited_size = _calc(fs, limit=FACTOR_SIZE) return total_size, limited_size @f_time def filesystem_directory_tree_size_second_recursion(file_path, output=None): output = output or read_filesystem_output(file_path) output = output.strip().split('\n') fs = create_filesystem_tree(output) total_size, limited_size = calculate_filesystem_tree_size(fs, limit=FACTOR_SIZE) return total_size, limited_size def find_directory_for_removal(file_path, output=None): output = output or read_filesystem_output(file_path) output = output.strip().split('\n') fs = create_filesystem_struct(output) USED_SPACE = fs['/'] print(USED_SPACE) min_space_for_removal = UNUSED_SPACE - (DISK_SPACE - USED_SPACE) directory, size = find_directory_specified_size(fs, min_space_for_removal) return directory, size def find_directory_specified_size(fs, size): """Caculate total size of directories with limited size""" print(size) dirs = [(k, v) for k, v in fs.items() if v in range(size, UNUSED_SPACE)] dirs = sorted(dirs, key=lambda d: d[1]) print(dirs) return dirs[0] def create_filesystem_tree(iterator): filesystem = dict() filesystem['/'] = {} path = [] cur_dir = filesystem['/'] for line in iterator: line_split = line.split() if '$' in line_split[0]: if 'ls' in line_split[1]: continue if 'cd' in line_split[1]: cd_opt = line_split[2] if cd_opt == '/': cur_dir = filesystem['/'] path = ['/'] elif cd_opt == '..': path.pop() cur_dir = filesystem for d in path: cur_dir = cur_dir[d] else: dir_name = f'/{cd_opt}' cur_dir = cur_dir[dir_name] path.append(dir_name) continue else: if 'dir' in line_split[0]: dir_name = f'/{line_split[1]}' cur_dir[dir_name] = {} continue size = int(line_split[0]) cur_dir[line_split[1]] = size return filesystem def _calc(d, limit, total_size=0): dir_size = 0 for k, v in d.items(): if isinstance(v, dict): size, total_size = _calc(v, limit, total_size) dir_size += size if limit and size < limit: total_size += size else: dir_size += v return dir_size, total_size def calc_dirs_size(d): size = 0 _d = d.copy() for k, v in _d.items(): if isinstance(v, dict): tmp = calc_dirs_size(v) d['dirs'] = tmp size += tmp else: size += v return size def calc_size(d, limit=0, total_size=0): dir_size = 0 for k, v in d.items(): if isinstance(v, dict): size, total_size = calc_size(v, limit, total_size) if limit and size <= limit: total_size += size else: dir_size += v return dir_size, total_size def calculate_filesystem_tree_size(fs, limit=0): total_dirs_size = calc_dirs_size(fs) total_size, limited_size = calc_size(fs, limit) assert total_dirs_size == total_size return total_size, limited_size def propage_size(fs, paths, size): for path in paths: fs[path] += size def create_filesystem_struct(iterator): """Prepare files system as paths with sizes interpretation""" filesystem = dict() paths = [] cur_dir = '/' filesystem[cur_dir] = 0 for line in iterator: line_split = line.split() if '$' in line_split[0]: if 'ls' in line_split[1]: continue if 'cd' in line_split[1]: cd_opt = line_split[2] if cd_opt == '/': cur_dir = '/' paths.clear() elif cd_opt == '..': cur_dir = paths.pop() else: paths.append(cur_dir) cur_dir = f'{cur_dir}/{cd_opt}' if cur_dir.strip('/') else f'/{cd_opt}' else: if 'dir' in line_split[0]: dir_name = line_split[1] if cur_dir == '/': ls_dir = f'/{dir_name}' else: ls_dir = f'{cur_dir}/{dir_name}' if ls_dir not in filesystem: filesystem[ls_dir] = 0 else: size = int(line_split[0]) filesystem[cur_dir] += size propage_size(filesystem, paths, size) return filesystem def calculate_directory_limited_size(fs, limit=0): """Caculate total size of directories with limited size""" if limit == 0: return fs['/'] size = 0 for k, v in fs.items(): if v <= limit: size += v return size ex_output = """ $ cd / $ ls dir a 14848514 b.txt 8504156 c.dat dir d $ cd a $ ls dir e 29116 f 2557 g 62596 h.lst $ cd e $ ls 584 i $ cd .. $ cd .. $ cd d $ ls 4060174 j 8033020 d.log 5626152 d.ext 7214296 k """ ex_struct = {'/': 48381165, '/a': 94853, '/d': 24933642, '/a/e': 584} def test_dir_structure(): iterator = ex_output.strip().split('\n') struct = create_filesystem_struct(iterator) assert (struct == ex_struct), ( f'Incorrect struct\nExpected: {ex_struct}\nActual: {struct}' ) SIZE_1KK = 95437 def test_calc_limited_size(): iterator = ex_output.strip().split('\n') struct = create_filesystem_struct(iterator) size = calculate_directory_limited_size(struct, limit=FACTOR_SIZE) assert size == SIZE_1KK, f'Incorrect size. Expected: {SIZE_1KK}. Actual: {size}' def test_calc_limited_tree_size(): iterator = ex_output.strip().split('\n') struct = create_filesystem_tree(iterator) total_size, limited_size = calculate_filesystem_tree_size(struct, limit=FACTOR_SIZE) assert limited_size == SIZE_1KK, f'Incorrect size. Expected: {SIZE_1KK}. Actual: {limited_size}' TOTAL_SIZE = 48381165 def test_calc_total_size(): iterator = ex_output.strip().split('\n') struct = create_filesystem_struct(iterator) size = calculate_directory_limited_size(struct) assert size == TOTAL_SIZE, f'Incorrect size. Expected: {TOTAL_SIZE}. Actual: {size}' def test_calc_total_tree_size(): iterator = ex_output.strip().split('\n') struct = create_filesystem_tree(iterator) size = calc_dirs_size(struct) assert size == TOTAL_SIZE, f'Incorrect size. Expected: {TOTAL_SIZE}. Actual: {size}' def test_removal_directory_closest_size(): ex_size = ex_struct['/d'] directory, size = find_directory_for_removal(file_path=FILE_PATH, output=ex_output) assert ex_size == size, ( f'Incorrect directory size for removal. Expected: {ex_size}. Actual: {size}') ex_filesystem = """ - / (dir) - a (dir) - E (dir) - i (file, size=584) - f (file, size=29116) - g (file, size=2557) - h.lst (file, size=62596) - b.txt (file, size=14848514) - c.dat (file, size=8504156) - d (dir) - j (file, size=4060174) - d.log (file, size=8033020) - d.ext (file, size=5626152) - k (file, size=7214296) """ """ The total sizes of the directories above can be found as follows: The total size of directory 'e' is 584 because it contains a single file 'i' of size 584 and no other directories. The directory 'a' has total size 94853 because it contains files: 'f' (size 29116), 'g' (size 2557), and 'h.lst' (size 62596), plus file 'i' indirectly (a contains e which contains i). Directory 'd' has total size 24933642. As the outermost directory, / contains every file. Its total size is 48381165, the sum of the size of every file. To begin, find all of the directories with a total size of at most 100000, then calculate the sum of their total sizes. In the example above, these directories are 'a' and 'e'; the sum of their total sizes is 95437 (94853 + 584). (As in this example, this process can count files more than once!) Find all of the directories with a total size of at most 100000. What is the sum of the total sizes of those directories? """ if __name__ == '__main__': file_path = sys.argv[1] if len(sys.argv) > 1 else FILE_PATH output = read_filesystem_output(file_path) print(filesystem_directory_structure_size(file_path, output)) print(filesystem_directory_tree_size(file_path, output)) print(filesystem_directory_tree_size_second_recursion(file_path, output)) print(find_directory_for_removal(file_path, output)) pytest.main(sys.argv) import os if (loop_no := os.getenv('LOOP_NO')) is None: exit() LOOP_NO = int(loop_no) print(filesystem_directory_structure_size(file_path, output)) print(filesystem_directory_tree_size(file_path, output)) print(filesystem_directory_tree_size_second_recursion(file_path, output))