Advertisement
Der_Teufel

AoC7

Dec 7th, 2020
932
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.61 KB | None | 0 0
  1. bags_desc = """...""".split("\n")
  2. def parse_line(line):
  3.     container, containees = line[:-1].split("contain")
  4.     containees = [x.split(maxsplit=1)[1].strip() for x in containees.split(',')]
  5.     containees = [x if x[-1] != 's' else x[:-1] for x in containees]
  6.     return containees, container.strip()[:-1]
  7.  
  8. def part1(bags):
  9.     bags_parse = list(map(parse_line, bags))
  10.     baggage = dict()
  11.     for e in bags_parse:
  12.         for containee in e[0]:
  13.             if containee not in baggage: baggage[containee] = set()
  14.             baggage[containee].add(e[1])
  15.     visited = set()
  16.     to_visit = []
  17.     to_visit += baggage['shiny gold bag']
  18.     while len(to_visit) > 0:
  19.         tmp = []
  20.         for e in to_visit:
  21.             if e in baggage:
  22.                 for k in baggage[e]:
  23.                     if k not in visited: tmp.append(k)
  24.             visited.add(e)
  25.         to_visit = tmp
  26.     return len(visited)
  27.  
  28. def parse_line_2(line):
  29.     things = [x.strip() for x in line[:-1].split('contain')]
  30.     things[1] = [x.strip() for x in things[1].split(',')]
  31.     things[0] = things[0][:-1]
  32.     things[1] = [x.split(maxsplit=1) for x in things[1]]
  33.     things[1] = [(x, y if y[-1] != 's' else y[:-1]) for x,y in things[1]]
  34.     return things
  35.  
  36. def packing(bag, multiplier, baggage_package):
  37.     packed = 0
  38.     if baggage_package[bag][0][0] == 'no': return 0
  39.     packed += sum(int(x[0]) for x in baggage_package[bag])
  40.     packed += sum(packing(bagn, count, baggage_package) for count, bagn in baggage_package[bag])
  41.     return int(multiplier)*packed
  42.  
  43. def part2(bags):
  44.     bags_parse = list(map(parse_line_2, bags))
  45.     baggage = dict()
  46.     for e in bags_parse:
  47.         baggage[e[0]] = e[1]
  48.     return packing('shiny gold bag', 1, baggage)
  49.  
  50. print(part1(bags_desc), part2(bags_desc))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement