Advertisement
rosien

Handy Haversacks_2020_Day7

Feb 28th, 2021
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.38 KB | None | 0 0
  1. with open('Day7.txt', 'rt') as f:
  2.     data = f.read().strip()
  3. data = data.split('.\n')
  4.  
  5. #Part 1:
  6. rules = {}
  7. import re
  8. pattern = r'[0-9]'
  9. for rule in data:
  10.     rule = rule.replace(' bags','').replace(' bag','')
  11.     outer_bag = rule.split(' contain ')[0]
  12.     inner_bag = rule.split(' contain ')[1]
  13.     inner_bag = re.sub(pattern, '',inner_bag)
  14.     if inner_bag.strip() == 'no other':
  15.         pass
  16.     else:
  17.         rules[outer_bag] = inner_bag.strip().split(',  ')
  18.  
  19. def recursive_dfs(graph, source,path = set()):
  20.     for key, value in graph.items():
  21.         if source in value:
  22. #             print('value:',value, 'key:', key )
  23.             path.add(key)
  24.             if recursive_dfs(graph, key, path) is None:
  25.                 path.add(i for i in recursive_dfs(graph, key, path))
  26.     return path
  27.  
  28. outer_bags = recursive_dfs(rules, "shiny gold")
  29.  
  30. len(outer_bags)
  31.  
  32. #part 2
  33. rules_2 = {}
  34. import re
  35. # pattern = r'[0-9]'
  36. for rule in data[:20]:
  37.     rule = rule.replace(' bags','').replace(' bag','')
  38.     outer_bag = rule.split(' contain ')[0]
  39.     inner_bag = rule.split(' contain ')[1]
  40.     if inner_bag.strip() == 'no other':
  41.         pass
  42.     else:
  43.         inner = []
  44.         for color in inner_bag.split(', '):
  45.             inner.append(color.split(" ", maxsplit = 1)[0])
  46.             inner.append(color.split(" ", maxsplit = 1)[1])
  47.         rules_2[outer_bag] =  inner
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement