1
+ import os
2
+
3
+ # read input
4
+ input = open ('dummy.txt' , 'r' )
5
+ lines = input .readlines ()
6
+ directories = {}
7
+ directorySize = {}
8
+ fileSystem = {}
9
+ totalSize = 0
10
+
11
+ # apply
12
+ for line in lines :
13
+ line = line .split ('\n ' )[0 ]
14
+ if (line [0 ] == '$' ):
15
+ ds , command , * directory = line .split ()
16
+ if (command == 'cd' ):
17
+ path = directory [0 ]
18
+ if (path == '/' ):
19
+ currentDirectory = path
20
+ else :
21
+ currentDirectory = os .path .normpath (os .path .join (currentDirectory , path ))
22
+ if (currentDirectory not in directories ):
23
+ directories [currentDirectory ] = []
24
+ fileSystem [currentDirectory ] = {
25
+ "path" : [],
26
+ "size" : 0 ,
27
+ "files" : {
28
+ "name" : [],
29
+ "size" : []
30
+ }
31
+ }
32
+ directorySize [currentDirectory ] = 0
33
+ else :
34
+ fileSize , fileName = line .split ()
35
+ if (fileSize != 'dir' ):
36
+ directorySize [currentDirectory ] += int (fileSize )
37
+ fileSystem [currentDirectory ]['size' ] += int (fileSize )
38
+ fileSystem [currentDirectory ]['files' ]['name' ].append (fileName )
39
+ fileSystem [currentDirectory ]['files' ]['size' ].append (int (fileSize ))
40
+ else :
41
+ directories [currentDirectory ].append (os .path .normpath (os .path .join (currentDirectory , fileName )))
42
+ fileSystem [currentDirectory ]['path' ].append (os .path .normpath (os .path .join (currentDirectory , fileName )))
43
+
44
+ # compute directory sizes
45
+ def computeDirectorySize (dirName : str ):
46
+ dirSize = directorySize [dirName ]
47
+ for item in directories [dirName ]:
48
+ if item in directories :
49
+ dirSize += computeDirectorySize (item )
50
+ return dirSize
51
+
52
+ for item in directories :
53
+ dirSize = computeDirectorySize (item )
54
+ if dirSize <= 100000 :
55
+ totalSize += dirSize
56
+
57
+ # second way
58
+ total = 0
59
+ def compute (name ):
60
+ size = fileSystem [name ]['size' ]
61
+ for i in fileSystem [name ]['path' ]:
62
+ if i in fileSystem :
63
+ size += compute (i )
64
+ return size
65
+
66
+ for key in fileSystem :
67
+ size = compute (key )
68
+ if size <= 100000 :
69
+ total += size
70
+
71
+ # print(fileSystem)
72
+ # print(directories)
73
+ # print(directorySize)
74
+ print (totalSize )
75
+ print (total )
0 commit comments