7.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. # Read lines
  2. lines = []
  3. with open("7.input") as f:
  4. for line in f.readlines():
  5. lines.append(line.strip().replace(".", ""))
  6. # Parse lines
  7. bags = {}
  8. for line in lines:
  9. words = line.split(" ")
  10. name = " ".join(words[0:2])
  11. bags[name] = []
  12. children = " ".join(words[4:]).split(",")
  13. if children == ["no other bags"]:
  14. continue
  15. for child in children:
  16. child = child.strip()
  17. words = child.split(" ")
  18. bags[name].append((int(words[0]), " ".join(words[1:3])))
  19. # Create inverse lookup table
  20. bag_parents = {}
  21. for (parent, children) in bags.items():
  22. for (_, child) in children:
  23. parents = bag_parents.get(child, [])
  24. parents.append(parent)
  25. bag_parents[child] = parents
  26. # Find all parents
  27. flatten = lambda t: [item for sublist in t for item in sublist]
  28. def find_parents(child):
  29. return flatten([[p] + find_parents(p) for p in bag_parents.get(child, [])])
  30. print("Answer 1: {}".format(len(set(find_parents("shiny gold")))))
  31. # Find all children
  32. def count_children(parent):
  33. return sum([c * (count_children(child) + 1) for (c, child) in bags[parent]])
  34. print("Answer 2: {}".format(count_children("shiny gold")))