Solutions to Advent of Code 2017 https://adventofcode.com/2017/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

07.py 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from types import SimpleNamespace
  2. programs = {}
  3. with open('data/07.txt', 'r') as file:
  4. for line in file.readlines():
  5. details = line.strip().split(' -> ')[0]
  6. children = line.strip().split(' -> ')[1].split(', ') if '->' in line else []
  7. name, weight = details.split(' ')
  8. weight = int(weight.strip('()'))
  9. programs[name] = SimpleNamespace(name=name, weight=weight, total_weight=-1, child_names=children, children=[])
  10. roots = list(programs.keys())
  11. leaves = []
  12. for program in list(programs.values()):
  13. for child in program.child_names:
  14. program.children.append(programs[child])
  15. programs[child].parent = program
  16. roots.remove(child)
  17. if len(program.children) == 0:
  18. leaves.append(program)
  19. def resolve_weight(program):
  20. if program.total_weight == -1:
  21. program.total_weight = program.weight + sum(resolve_weight(child) for child in program.children)
  22. return program.total_weight
  23. def check_weight(program):
  24. weights = [child.total_weight for child in program.children]
  25. for child in program.children:
  26. if weights.count(child.total_weight) == 1:
  27. return check_weight(child) or next(w for w in weights if w != child.total_weight) - sum(c.total_weight for c in child.children)
  28. resolve_weight(programs[roots[0]])
  29. print(f'Part one: {programs[roots[0]].name}')
  30. print(f'Part two: {check_weight(programs[roots[0]])}')