Solutions to Advent of Code 2017 https://adventofcode.com/2017/
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

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