28/38
Part 6 of 7 · The worked exampleLearn
A change moves only the totals on its path to the top
3. The insight. A change to one file moves exactly the totals of the folders that contain it: its ancestors, the path from it to the top. Nothing else. So store every node's total once, with one post-order pass. On a change, walk up parent adding the difference. A read becomes a lookup.
from collections import defaultdict
class SizeTree:
def __init__(self, pairs, file_sizes):
self.parent, self.children = {}, defaultdict(list)
for item, folder in pairs:
self.parent[item] = folder
self.children[folder].append(item)
top = next(folder for _, folder in pairs if folder not in self.parent)
# bytes stored at the node itself
self.own = defaultdict(int, file_sizes)
order, stack = [], [top]
while stack:
node = stack.pop()
order.append(node)
stack.extend(self.children[node])
self.total = {}
# backwards: post-order, as with sizes_with_stack
for node in reversed(order):
self.total[node] = self.own[node] + sum(self.total[c] for c in self.children[node])
def size_of(self, node):
return self.total[node]
def resize(self, file, size):
change = size - self.own[file]
self.own[file] = size
node = file
# the file, then each folder above it
while node is not None:
self.total[node] += change
node = self.parent.get(node)
tree = SizeTree(PAIRS, SIZES)
print([tree.size_of(node) for node in ["/", "docs", "photos", "2024"]])
tree.resize("trip.jpg", 1500)
print([tree.size_of(node) for node in ["/", "docs", "photos", "2024"]])
photos holds beach.jpg (2300 bytes) and the folder 2024, which holds trip.jpg (1800). What's size_of("photos") before the resize?
Pick one to see what it prints.
resize("trip.jpg", 1500) on a file of 1800 bytes. What does the walk add to each total on its way up?
Pick an answer above to see the rest