#!/usr/bin/env python # 2022 - Advent Of Code 7 file = 'input_example.txt' file = 'input.txt' dir_history = "" dir_size = {} cur_dir = '' with open(file, encoding="utf-8") as f: for line in f.readlines(): if line.startswith('$'): command = line.strip().split(' ')[1] # print(f'command: {command} received') if command == 'ls': print(f'listing directory {dir_history}') elif command == 'cd': new_dir = line.strip().split(' ')[2] if new_dir == '..': cur_size = dir_size[dir_history] dir_history = dir_history[:dir_history.rfind('/')] dir_size[dir_history] += cur_size print(f'back to directory {dir_history}') else: if new_dir.endswith('/'): dir_history += new_dir else: dir_history += "/" + new_dir print(f'changing directory to {dir_history}') dir_size[dir_history] = 0 else: if line.startswith('dir'): directory = line.strip().split(' ')[1] print(f'found dir {directory}') else: size, filename = line.strip().split(' ') print(f'found file {filename} of size {size}') dir_size[dir_history] += int(size) # back to root to account dirs while len(dir_history) > 1: cur_size = dir_size[dir_history] dir_history = dir_history[:dir_history.rfind('/')] dir_size[dir_history] += cur_size print(dir_size) sum_size = 0 for i in dir_size.values(): if i <= 100000: sum_size += i print(sum_size)