My Advent of Code solutions in Python. kevinyap.ca/2019/12/going-fast-in-advent-of-code/
advent-of-code python
0
fork

Configure Feed

Select the types of activity you want to include in your feed.

Add 2022/07

+68
+68
2022/day07.py
··· 1 + import fileinput 2 + 3 + 4 + class File: 5 + def __init__(self, name, size=0): 6 + self.name = name 7 + self.size = size 8 + self.children = [] 9 + self.parent = None 10 + 11 + FS = File('/') 12 + pwd = FS 13 + 14 + for line in fileinput.input(): 15 + if line.startswith('$'): 16 + parts = line.split() 17 + cmd = parts[1] 18 + if cmd == 'cd': 19 + directory = parts[2] 20 + if directory == '..': 21 + pwd = pwd.parent 22 + else: # cd-ing into a new directory 23 + file = File(directory) 24 + file.parent = pwd 25 + pwd.children.append(file) 26 + pwd = file 27 + 28 + # The current line is telling us something about 29 + # either a file and its size, or a new directory. 30 + else: 31 + size, name = line.split() 32 + 33 + # Only care if we are looking at a file. 34 + if size != 'dir': 35 + file = File(name, int(size)) 36 + pwd.children.append(file) 37 + 38 + 39 + SIZES = {} 40 + 41 + def dir_size(file): 42 + """Return the size of the given file.""" 43 + if not file.children: 44 + return file.size 45 + 46 + total_size = 0 47 + for child in file.children: 48 + total_size += dir_size(child) 49 + 50 + SIZES[file] = total_size 51 + return total_size 52 + 53 + # Perform DFS to seed `SIZES`. 54 + USED = dir_size(FS) 55 + 56 + # Part 1 57 + print("Part 1:", sum(s for s in SIZES.values() if s < 100000)) 58 + 59 + # Part 2 60 + AVAILABLE = 70000000 61 + NEED = 30000000 62 + UNUSED = AVAILABLE - USED 63 + 64 + for size in sorted(SIZES.values()): 65 + if UNUSED + size >= NEED: 66 + print("Part 2:", size) 67 + break 68 +