Advertisement
hhoppe

Advent of code 2020 day 6

Dec 7th, 2020 (edited)
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.74 KB | None | 0 0
  1. def get_contents(s):
  2.   contents = {}
  3.   for line in s.strip('\n').split('\n'):
  4.     outer, inners = line.split(' bags contain ')
  5.     contents[outer] = {}
  6.     for match in re.finditer(r'(\d+) (.*?) bags?[,.]', inners):
  7.       n, inner = match.groups()
  8.       contents[outer][inner] = int(n)
  9.   return contents
  10.  
  11.  
  12. def count_containers(s, query='shiny gold'):
  13.   contents = get_contents(s)
  14.  
  15.   def valid(bag):
  16.     return any(inner == query or valid(inner) for inner in contents[bag])
  17.  
  18.   return sum(valid(bag) for bag in contents)
  19.  
  20.  
  21. def count_total_inside(s, query='shiny gold'):
  22.   contents = get_contents(s)
  23.  
  24.   def count_inside(bag):
  25.     return sum(n * (count_inside(b) + 1) for b, n in contents[bag].items())
  26.  
  27.   return count_inside(query)
  28.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement