Guest User

aoc_2022_day_07

a guest
Dec 9th, 2022
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.31 KB | None | 0 0
  1. #!/usr/bin/env python3.8
  2. """
  3. Within the terminal output, lines that begin with $ are commands you executed,
  4. very much like some modern computers:
  5.  
  6. cd means change directory.
  7. This changes which directory is the current directory,
  8. but the specific result depends on the argument:
  9. cd x moves in one level:
  10. it looks in the current directory for the directory named x and makes it the current directory.
  11. cd .. moves out one level:
  12. it finds the directory that contains the current directory,
  13. then makes that directory the current directory.
  14. cd / switches the current directory to the outermost directory, /.
  15. ls means list.
  16. It prints out all of the files and directories immediately contained by the current directory:
  17. 123 abc means that the current directory contains a file named abc with size 123.
  18. dir xyz means that the current directory contains a directory named xyz.
  19.  
  20. """
  21. import sys
  22. from pathlib import Path
  23. import pytest
  24. import time
  25. from functools import wraps
  26.  
  27. INPUTS_DIR = 'inputs'
  28. INPUT_FILE = 'day07.txt'
  29. PROJECT_DIR = Path('.')
  30. FILE_PATH = PROJECT_DIR / INPUTS_DIR / INPUT_FILE
  31. LOOP_NO = 1
  32.  
  33.  
  34. def f_time(f):
  35.     @wraps(f)
  36.     def time_check(*args, **kwargs):
  37.         print(f'{LOOP_NO=}')
  38.         start_time = time.monotonic()
  39.         for i in range(LOOP_NO):
  40.             sizes = f(*args, *kwargs)
  41.         end_time = time.monotonic()
  42.         print(f"It took {end_time-start_time:.10f} seconds to compute")
  43.         return sizes
  44.     return time_check
  45.  
  46.  
  47. FACTOR_SIZE = 10**5
  48. DISK_SPACE = 7*10**7
  49. UNUSED_SPACE = 3*10**7
  50.  
  51.  
  52. def read_filesystem_output(file_path):
  53.     with open(file_path) as f:
  54.         return f.read()
  55.  
  56.  
  57. @f_time
  58. def filesystem_directory_structure_size(file_path, output=None):
  59.     output = output or read_filesystem_output(file_path)
  60.     output = output.strip().split('\n')
  61.     fs = create_filesystem_struct(output)
  62.     calc_dir_1kk = calculate_directory_limited_size(fs, limit=FACTOR_SIZE)
  63.     return calc_dir_1kk
  64.  
  65.  
  66. @f_time
  67. def filesystem_directory_tree_size(file_path, output=None):
  68.     output = output or read_filesystem_output(file_path)
  69.     output = output.strip().split('\n')
  70.     fs = create_filesystem_tree(output)
  71.     total_size, limited_size = _calc(fs, limit=FACTOR_SIZE)
  72.     return total_size, limited_size
  73.  
  74.  
  75. @f_time
  76. def filesystem_directory_tree_size_second_recursion(file_path, output=None):
  77.     output = output or read_filesystem_output(file_path)
  78.     output = output.strip().split('\n')
  79.     fs = create_filesystem_tree(output)
  80.     total_size, limited_size = calculate_filesystem_tree_size(fs, limit=FACTOR_SIZE)
  81.     return total_size, limited_size
  82.  
  83.  
  84. def find_directory_for_removal(file_path, output=None):
  85.     output = output or read_filesystem_output(file_path)
  86.     output = output.strip().split('\n')
  87.     fs = create_filesystem_struct(output)
  88.     USED_SPACE = fs['/']
  89.     print(USED_SPACE)
  90.     min_space_for_removal = UNUSED_SPACE - (DISK_SPACE - USED_SPACE)
  91.     directory, size = find_directory_specified_size(fs, min_space_for_removal)
  92.     return directory, size
  93.  
  94.  
  95. def find_directory_specified_size(fs, size):
  96.     """Caculate total size of directories with limited size"""
  97.     print(size)
  98.     dirs = [(k, v) for k, v in fs.items() if v in range(size, UNUSED_SPACE)]
  99.     dirs = sorted(dirs, key=lambda d: d[1])
  100.     print(dirs)
  101.     return dirs[0]
  102.  
  103.  
  104. def create_filesystem_tree(iterator):
  105.     filesystem = dict()
  106.     filesystem['/'] = {}
  107.     path = []
  108.     cur_dir = filesystem['/']
  109.     for line in iterator:
  110.         line_split = line.split()
  111.         if '$' in line_split[0]:
  112.             if 'ls' in line_split[1]:
  113.                 continue
  114.             if 'cd' in line_split[1]:
  115.                 cd_opt = line_split[2]
  116.                 if cd_opt == '/':
  117.                     cur_dir = filesystem['/']
  118.                     path = ['/']
  119.                 elif cd_opt == '..':
  120.                     path.pop()
  121.                     cur_dir = filesystem
  122.                     for d in path:
  123.                         cur_dir = cur_dir[d]
  124.                 else:
  125.                     dir_name = f'/{cd_opt}'
  126.                     cur_dir = cur_dir[dir_name]
  127.                     path.append(dir_name)
  128.                 continue
  129.         else:
  130.             if 'dir' in line_split[0]:
  131.                 dir_name = f'/{line_split[1]}'
  132.                 cur_dir[dir_name] = {}
  133.                 continue
  134.             size = int(line_split[0])
  135.             cur_dir[line_split[1]] = size
  136.     return filesystem
  137.  
  138.  
  139. def _calc(d, limit, total_size=0):
  140.     dir_size = 0
  141.     for k, v in d.items():
  142.         if isinstance(v, dict):
  143.             size, total_size = _calc(v, limit, total_size)
  144.             dir_size += size
  145.             if limit and size < limit:
  146.                 total_size += size
  147.         else:
  148.             dir_size += v
  149.     return dir_size, total_size
  150.  
  151.  
  152. def calc_dirs_size(d):
  153.     size = 0
  154.     _d = d.copy()
  155.     for k, v in _d.items():
  156.         if isinstance(v, dict):
  157.             tmp = calc_dirs_size(v)
  158.             d['dirs'] = tmp
  159.             size += tmp
  160.         else:
  161.             size += v
  162.     return size
  163.  
  164.  
  165. def calc_size(d, limit=0, total_size=0):
  166.     dir_size = 0
  167.     for k, v in d.items():
  168.         if isinstance(v, dict):
  169.             size, total_size = calc_size(v, limit, total_size)
  170.             if limit and size <= limit:
  171.                 total_size += size
  172.         else:
  173.             dir_size += v
  174.     return dir_size, total_size
  175.  
  176.  
  177. def calculate_filesystem_tree_size(fs, limit=0):
  178.     total_dirs_size = calc_dirs_size(fs)
  179.     total_size, limited_size = calc_size(fs, limit)
  180.     assert total_dirs_size == total_size
  181.     return total_size, limited_size
  182.  
  183.  
  184. def propage_size(fs, paths, size):
  185.     for path in paths:
  186.         fs[path] += size
  187.  
  188.  
  189. def create_filesystem_struct(iterator):
  190.     """Prepare files system as paths with sizes interpretation"""
  191.     filesystem = dict()
  192.     paths = []
  193.     cur_dir = '/'
  194.     filesystem[cur_dir] = 0
  195.     for line in iterator:
  196.         line_split = line.split()
  197.         if '$' in line_split[0]:
  198.             if 'ls' in line_split[1]:
  199.                 continue
  200.             if 'cd' in line_split[1]:
  201.                 cd_opt = line_split[2]
  202.                 if cd_opt == '/':
  203.                     cur_dir = '/'
  204.                     paths.clear()
  205.                 elif cd_opt == '..':
  206.                     cur_dir = paths.pop()
  207.                 else:
  208.                     paths.append(cur_dir)
  209.                     cur_dir = f'{cur_dir}/{cd_opt}' if cur_dir.strip('/') else f'/{cd_opt}'
  210.         else:
  211.             if 'dir' in line_split[0]:
  212.                 dir_name = line_split[1]
  213.                 if cur_dir == '/':
  214.                     ls_dir = f'/{dir_name}'
  215.                 else:
  216.                     ls_dir = f'{cur_dir}/{dir_name}'
  217.                 if ls_dir not in filesystem:
  218.                     filesystem[ls_dir] = 0
  219.             else:
  220.                 size = int(line_split[0])
  221.                 filesystem[cur_dir] += size
  222.                 propage_size(filesystem, paths, size)
  223.     return filesystem
  224.  
  225.  
  226. def calculate_directory_limited_size(fs, limit=0):
  227.     """Caculate total size of directories with limited size"""
  228.     if limit == 0:
  229.         return fs['/']
  230.     size = 0
  231.     for k, v in fs.items():
  232.         if v <= limit:
  233.             size += v
  234.     return size
  235.  
  236.  
  237. ex_output = """
  238. $ cd /
  239. $ ls
  240. dir a
  241. 14848514 b.txt
  242. 8504156 c.dat
  243. dir d
  244. $ cd a
  245. $ ls
  246. dir e
  247. 29116 f
  248. 2557 g
  249. 62596 h.lst
  250. $ cd e
  251. $ ls
  252. 584 i
  253. $ cd ..
  254. $ cd ..
  255. $ cd d
  256. $ ls
  257. 4060174 j
  258. 8033020 d.log
  259. 5626152 d.ext
  260. 7214296 k
  261. """
  262.  
  263. ex_struct = {'/': 48381165, '/a': 94853, '/d': 24933642, '/a/e': 584}
  264.  
  265.  
  266. def test_dir_structure():
  267.     iterator = ex_output.strip().split('\n')
  268.     struct = create_filesystem_struct(iterator)
  269.     assert (struct == ex_struct), (
  270.         f'Incorrect struct\nExpected: {ex_struct}\nActual: {struct}'
  271.     )
  272.  
  273.  
  274. SIZE_1KK = 95437
  275.  
  276.  
  277. def test_calc_limited_size():
  278.     iterator = ex_output.strip().split('\n')
  279.     struct = create_filesystem_struct(iterator)
  280.     size = calculate_directory_limited_size(struct, limit=FACTOR_SIZE)
  281.     assert size == SIZE_1KK, f'Incorrect size. Expected: {SIZE_1KK}. Actual: {size}'
  282.  
  283.  
  284. def test_calc_limited_tree_size():
  285.     iterator = ex_output.strip().split('\n')
  286.     struct = create_filesystem_tree(iterator)
  287.     total_size, limited_size = calculate_filesystem_tree_size(struct, limit=FACTOR_SIZE)
  288.     assert limited_size == SIZE_1KK, f'Incorrect size. Expected: {SIZE_1KK}. Actual: {limited_size}'
  289.  
  290.  
  291. TOTAL_SIZE = 48381165
  292.  
  293.  
  294. def test_calc_total_size():
  295.     iterator = ex_output.strip().split('\n')
  296.     struct = create_filesystem_struct(iterator)
  297.     size = calculate_directory_limited_size(struct)
  298.     assert size == TOTAL_SIZE, f'Incorrect size. Expected: {TOTAL_SIZE}. Actual: {size}'
  299.  
  300.  
  301. def test_calc_total_tree_size():
  302.     iterator = ex_output.strip().split('\n')
  303.     struct = create_filesystem_tree(iterator)
  304.     size = calc_dirs_size(struct)
  305.     assert size == TOTAL_SIZE, f'Incorrect size. Expected: {TOTAL_SIZE}. Actual: {size}'
  306.  
  307.  
  308. def test_removal_directory_closest_size():
  309.     ex_size = ex_struct['/d']
  310.     directory, size = find_directory_for_removal(file_path=FILE_PATH, output=ex_output)
  311.     assert ex_size == size, (
  312.         f'Incorrect directory size for removal. Expected: {ex_size}. Actual: {size}')
  313.  
  314.  
  315. ex_filesystem = """
  316. - / (dir)
  317.  - a (dir)
  318.    - E (dir)
  319.      - i (file, size=584)
  320.    - f (file, size=29116)
  321.    - g (file, size=2557)
  322.    - h.lst (file, size=62596)
  323.  - b.txt (file, size=14848514)
  324.  - c.dat (file, size=8504156)
  325.  - d (dir)
  326.    - j (file, size=4060174)
  327.    - d.log (file, size=8033020)
  328.    - d.ext (file, size=5626152)
  329.    - k (file, size=7214296)
  330. """
  331.  
  332. """
  333. The total sizes of the directories above can be found as follows:
  334.  
  335. The total size of directory 'e' is 584
  336. because it contains a single file 'i' of size 584 and no other directories.
  337.  
  338. The directory 'a' has total size 94853
  339. because it contains files:
  340. 'f' (size 29116),
  341. 'g' (size 2557), and
  342. 'h.lst' (size 62596), plus file 'i' indirectly (a contains e which contains i).
  343.  
  344. Directory 'd' has total size 24933642.
  345. As the outermost directory, / contains every file.
  346. Its total size is 48381165, the sum of the size of every file.
  347.  
  348. To begin, find all of the directories with a total size of at most 100000,
  349. then calculate the sum of their total sizes.
  350.  
  351. In the example above, these directories are 'a' and 'e';
  352. the sum of their total sizes is 95437 (94853 + 584).
  353. (As in this example, this process can count files more than once!)
  354.  
  355. Find all of the directories with a total size of at most 100000.
  356. What is the sum of the total sizes of those directories?
  357. """
  358.  
  359. if __name__ == '__main__':
  360.     file_path = sys.argv[1] if len(sys.argv) > 1 else FILE_PATH
  361.     output = read_filesystem_output(file_path)
  362.  
  363.     print(filesystem_directory_structure_size(file_path, output))
  364.  
  365.     print(filesystem_directory_tree_size(file_path, output))
  366.  
  367.     print(filesystem_directory_tree_size_second_recursion(file_path, output))
  368.  
  369.     print(find_directory_for_removal(file_path, output))
  370.  
  371.     pytest.main(sys.argv)
  372.  
  373.     import os
  374.     if (loop_no := os.getenv('LOOP_NO')) is None:
  375.         exit()
  376.     LOOP_NO = int(loop_no)
  377.     print(filesystem_directory_structure_size(file_path, output))
  378.  
  379.     print(filesystem_directory_tree_size(file_path, output))
  380.  
  381.     print(filesystem_directory_tree_size_second_recursion(file_path, output))
  382.  
Advertisement
Add Comment
Please, Sign In to add comment