You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

56 lines
1.6 KiB
Python

2 years ago
#!/usr/bin/env python3
import re
INPUT_FILE = 'input'
cd_pattern = '^\$\scd (.*)$'
ls_pattern = '^\$ ls$'
dir_pattern = '^dir .*$'
file_pattern = '^(\d+) .*$'
total_space = 70000000
required_free = 30000000
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)
used_space = folders['//']
free_space = total_space - used_space
print('total: {} used: {} free: {}'.format(total_space, used_space, free_space))
space_needed = required_free - free_space
print('Need {}'.format(space_needed))
candidates = []
for key in folders.keys():
if folders[key] >= space_needed:
candidates.append(folders[key])
print('Result: {}'.format(min(candidates)))
if __name__ == '__main__':
main()