adventofcode/2022/07/01.py

52 lines
1.3 KiB
Python
Raw Normal View History

2022-12-08 19:33:23 +01:00
#!/usr/bin/env python3
import re
INPUT_FILE = 'input'
cd_pattern = '^\$\scd (.*)$'
ls_pattern = '^\$ ls$'
dir_pattern = '^dir .*$'
file_pattern = '^(\d+) .*$'
def main():
content = map(str.strip, open(INPUT_FILE, 'r').readlines())
cwd = ['']
folders = {}
for line in content:
if re.match(dir_pattern, line) or re.match(ls_pattern, line):
# ignore `dir a` and `$ ls`
continue
cd = re.match(cd_pattern, line)
if cd:
new_dir = cd.group(1)
if new_dir == '..':
cwd.pop()
else:
cwd.append(new_dir)
folders['/'.join(cwd)] = 0
print('/'.join(cwd))
continue
file_match = re.match(file_pattern, line)
if file_match:
filesize = int(file_match.group(1))
for n in range(len(cwd), 0, -1):
try:
folders['/'.join(cwd[:n])] += filesize
except KeyError:
continue
else:
print('ERROR: No regex matched for {}'.format(line()))
print(folders)
dir_sum = 0
for key in folders.keys():
if folders[key] <= 100000:
dir_sum += folders[key]
print(key, dir_sum)
print(dir_sum)
if __name__ == '__main__':
main()