aoc/2022/day07.py

98 lines
2.5 KiB
Python

#!/usr/bin/env python3
from typing import TextIO
def join(cwd: list, upto: int) -> str:
path = ""
for i in range(upto + 1):
path = path + "/" + cwd[i]
return path
def part1(t_out: TextIO) -> int:
files = {}
cwd = ""
tot = 0
line = t_out.readline().strip()
while line != "":
# parse commands here
print(line)
print(files)
if line == "$ cd /":
cwd = "/"
line = t_out.readline().strip()
elif line == "$ cd ..":
cwd = "/" + cwd.strip("/")[:-1][:-1]
line = t_out.readline().strip()
elif line.split()[:2] == ["$", "cd"]:
if not cwd == "/":
cwd += f"/{line.split()[2]}"
else:
cwd += f"{line.split()[2]}"
line = t_out.readline().strip()
print(">", cwd)
if line == "$ ls":
line = t_out.readline().strip()
while line != "" and line.split()[0] != "$":
lspl = line.split()
# print("here", lspl)
if lspl[0] == "dir": # mkdir
if not cwd == "/":
files[f"{cwd}/{lspl[1]}"] = 0
else:
files[f"{cwd}{lspl[1]}"] = 0
print(files)
else:
# print(cwd, len(cwd.split("/")))
if len(cwd.split("/")) not in (1, 2): # not like /aaa, has multiple
recdirs = cwd.split("/")[1:]
ls = []
for i in range(len(recdirs)):
ls.append(join(recdirs, i))
print(ls)
for path in ls:
files[path] += int(lspl[0])
elif (
len(cwd.split("/")) == 2 and cwd.split("/")[1] != ""
): # only one of /a, not root
# print(cwd, "run only /[...]")
files[cwd] += int(lspl[0])
tot += int(lspl[0]) # "/" case here
# PARSE HERE!!
# file: add to both current folder dict and previous
# from thinking in bed: full path as key, add to each in for...
line = t_out.readline().strip()
print(files)
print("total", tot)
sum = 0
for i in files:
if files[i] < 100000:
sum += files[i]
return sum
print(part1(open("day07.txt")))