import re import argparse parser = argparse.ArgumentParser() parser.add_argument("filename", help="the file from which to take data") args = parser.parse_args() with open(args.filename, "r") as f: contents = f.read() root = {"/": {}} pwd = ["/"] for command in contents.split("$"): command = command.strip() current_directory = root for directory in pwd: current_directory = current_directory[directory] if command.startswith("cd"): if "cd /" in command: pwd = ["/"] elif ".." in command: pwd.pop() else: pwd.append(command.split()[1]) print("moved. now our location is {}", pwd) if command.startswith("ls"): for line in command.split("\n"): if line == "ls": continue else: line = line.split() if line[0] == "dir": if line[1] not in current_directory: current_directory[line[1]] = {} else: current_directory[line[1]] = int(line[0]) # add to the directory listing pass print("a command: {}".format(command)) def size_of_listing(path): it = root for i in path: it = it[i] if isinstance(it, dict): s = 0 for k, v in it.items(): s += size_of_listing(path + [k]) return s return it def all_of_it(path, d): for k, v in d.items(): if isinstance(v, dict): yield from all_of_it(path + [k], v) yield path + [k], size_of_listing(path + [k]) total_space = 70000000 total_needed = 30000000 space_used = size_of_listing(["/"]) free_space = total_space-space_used required = total_needed - free_space s=0 for path, size in sorted(list(all_of_it(["/"], root["/"])), key=lambda x: x[1]): print("{} with size {}".format(path, size)) if size < 100000: s += size print("total less than 100,000 is {}".format(s)) for path, size in filter( lambda x: x[1] > required, sorted( list( all_of_it(["/"], root["/"]) ), key=lambda x: x[1] ) ): print("{} with size {}".format(path, size))