-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday07_no_space_left_on_device.py
More file actions
82 lines (69 loc) · 1.8 KB
/
Copy pathday07_no_space_left_on_device.py
File metadata and controls
82 lines (69 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#!/usr/bin/env python3
from typing import Optional
class Dir:
def __init__(self, parent) -> None:
self.parent = parent
self.dirs: dict[str, Dir] = {}
self.files: dict[str, File] = {}
@property
def size(self) -> int:
return sum(x.size for x in list(self.dirs.values()) + list(self.files.values()))
class File:
def __init__(self, size: int, parent: Dir) -> None:
self.size = size
self.parent = parent
def main(terminal: str) -> None:
root: Optional[Dir] = None
cwd: Optional[Dir] = None
dirs: list[Dir] = []
for line in terminal.splitlines():
if line[0] == "$":
cmd, *args = line[1:].split()
if cmd == "cd":
if root is None:
root = Dir(None)
dirs.append(root)
cwd = root
else:
if args[0] == "..":
cwd = cwd.parent
else:
cwd = cwd.dirs[args[0]]
else:
size, name = line.split()
try:
cwd.files[name] = File(int(size), cwd)
except ValueError:
directory = Dir(cwd)
dirs.append(directory)
cwd.dirs[name] = directory
print("Part One:")
print(sum(dir.size for dir in dirs if dir.size <= 100_000))
print("Part Two:")
print(min(dir.size for dir in dirs if root.size - dir.size <= 40_000_000))
if __name__ == "__main__":
INPUT = """$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k
"""
main(INPUT)