Add solution for day 07
This commit is contained in:
1 parent
66451e31d2
commit
f622a647c7
4 files changed
+1293
No files matched your search
Executable
+61
@@ -0,0 +1,61 @@
|
||||
#!/usr/bin/env python3
|
||||
|
||||
import sys
|
||||
import numpy as np
|
||||
|
||||
DIRS = {}
|
||||
|
||||
def init(d):
|
||||
DIRS[d] = {}
|
||||
DIRS[d]['parent'] = DIRS['current']
|
||||
DIRS[d]['size'] = 0
|
||||
DIRS[d]['files'] = []
|
||||
DIRS[d]['children'] = []
|
||||
|
||||
def interpret(line):
|
||||
if line == '$ cd /':
|
||||
DIRS['current'] = '/'
|
||||
return
|
||||
elif line == '$ ls': return
|
||||
com = line.split(' ')
|
||||
if com[1] == 'cd':
|
||||
if com[2] == '..': DIRS['current'] = DIRS[DIRS['current']]['parent']
|
||||
else: DIRS['current'] = f'{DIRS["current"]}-{com[2]}'
|
||||
elif com[0] == 'dir':
|
||||
init(f'{DIRS["current"]}-{com[1]}')
|
||||
DIRS[DIRS['current']]['children'].append(f'{DIRS["current"]}-{com[1]}')
|
||||
else: DIRS[DIRS['current']]['files'].append(int(com[0]))
|
||||
|
||||
def calc_size(d):
|
||||
info = DIRS[d]
|
||||
size = 0
|
||||
for c in info['children']:
|
||||
if DIRS[c]['size'] == 0: calc_size(c)
|
||||
size = size + DIRS[c]['size']
|
||||
info['size'] = size + np.sum(info['files'])
|
||||
|
||||
if __name__ == '__main__':
|
||||
terminal = [line.strip('\n') for line in open(sys.argv[1])]
|
||||
DIRS['current'] = ''
|
||||
init('/')
|
||||
for t in terminal: interpret(t)
|
||||
calc_size('/')
|
||||
|
||||
s = 0
|
||||
for d in DIRS.keys():
|
||||
if d != 'current':
|
||||
if DIRS[d]['size'] <= 100000: s = s + DIRS[d]['size']
|
||||
|
||||
# challenge 1
|
||||
res1 = str(s)
|
||||
print("challenge 1:" + "\n" + res1 + "\n")
|
||||
|
||||
# challenge 2
|
||||
n = 30000000 - (70000000 - DIRS['/']['size'])
|
||||
s = 70000000
|
||||
for d in DIRS.keys():
|
||||
if d != 'current':
|
||||
if s > DIRS[d]['size'] >= n: s = DIRS[d]['size']
|
||||
res2 = str(s)
|
||||
print("challenge 2:" + "\n" + res2 + "\n")
|
||||
|
||||
Reference in new issue
Block a user