7.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. lines = [line.strip().split(" ") for line in open("7.input").readlines()]
  2. def insert_node(root, path, name, node):
  3. current = root
  4. for part in path:
  5. current = current["children"][part]
  6. current["children"][name] = node
  7. def parse(lines):
  8. root = {"children": {}}
  9. pwd = []
  10. for line in lines:
  11. if line[0] == "$":
  12. if line[1] == "cd":
  13. if line[2] == "/":
  14. pwd = []
  15. elif line[2] == "..":
  16. pwd = pwd[:-1]
  17. else:
  18. pwd.append(line[2])
  19. elif line[1] == "ls":
  20. pass
  21. elif line[0] == "dir":
  22. insert_node(root, pwd, line[1], {"children": {}})
  23. else:
  24. insert_node(root, pwd, line[1], {"size": int(line[0])})
  25. return root
  26. def calc_size(node):
  27. if "size" not in node:
  28. node["size"] = sum(calc_size(child) for child in node["children"].values())
  29. return node["size"]
  30. def all_dirs(node, name):
  31. if "children" in node:
  32. return [(node['size'], name)] + \
  33. [dir for name, child in node["children"].items() for dir in all_dirs(child, name)]
  34. else:
  35. return []
  36. def part1(root):
  37. return sum(size for size, name in all_dirs(root, "/") if size <= 100000)
  38. def part2(root):
  39. total = 70000000
  40. required = 30000000
  41. used = root["size"]
  42. to_delete = required - (total - used)
  43. dirs = all_dirs(root, "/")
  44. for size, _ in sorted(dirs):
  45. if size >= to_delete:
  46. return size
  47. return 0
  48. root_node = parse(lines)
  49. calc_size(root_node)
  50. print(part1(root_node))
  51. print(part2(root_node))