Advent of Code 2022 day 7

Kept using the number 4 million instead of 40 million for part 2. Need to look closer next time. Replicating the filesystem was fun. reading was totally unnecessary, could have just left out the ls case.

with open("7.txt") as f:
    lines = f.read().splitlines()

filesystem = {}
cwd = "/"

reading = False
for line in lines:
    # command
    if line.startswith("$"):
        reading = False
        # cd
        if line.startswith("$ cd "):
            d = line.split("$ cd ")[1]
            if d == "/":
                cwd = "/"
            elif d == "..":
                cwd = "/".join(cwd.split("/")[:-2])+"/"
            else:
                cwd += d+"/"
        # ls
        elif line == "$ ls":
            reading = True
    else:
        # init if not in
        if cwd not in filesystem:
            filesystem[cwd] = []
        # dir
        if line.startswith("dir"):
            filesystem[cwd].append(line.split(" ")[1])
        else:
            filesystem[cwd].append(int(line.split(" ")[0]))

def d_size(d):
    sum = 0
    for f in filesystem[d]:
        if type(f) is int:
            sum += f
        else:
            sum += d_size(d+f+"/")
    return sum

total = 0
for d in filesystem:
    if d_size(d) < 100000:
        total += d_size(d)
print(total)

# part 2
dir_sizes = {d: d_size(d) for d in filesystem}
cur_size = dir_sizes["/"]

print(min(size for _, size in dir_sizes.items() if cur_size-size < 40000000))