Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- with open('Day7.txt', 'rt') as f:
- data = f.read().strip()
- data = data.split('.\n')
- #Part 1:
- rules = {}
- import re
- pattern = r'[0-9]'
- for rule in data:
- rule = rule.replace(' bags','').replace(' bag','')
- outer_bag = rule.split(' contain ')[0]
- inner_bag = rule.split(' contain ')[1]
- inner_bag = re.sub(pattern, '',inner_bag)
- if inner_bag.strip() == 'no other':
- pass
- else:
- rules[outer_bag] = inner_bag.strip().split(', ')
- def recursive_dfs(graph, source,path = set()):
- for key, value in graph.items():
- if source in value:
- # print('value:',value, 'key:', key )
- path.add(key)
- if recursive_dfs(graph, key, path) is None:
- path.add(i for i in recursive_dfs(graph, key, path))
- return path
- outer_bags = recursive_dfs(rules, "shiny gold")
- len(outer_bags)
- #part 2
- rules_2 = {}
- import re
- # pattern = r'[0-9]'
- for rule in data[:20]:
- rule = rule.replace(' bags','').replace(' bag','')
- outer_bag = rule.split(' contain ')[0]
- inner_bag = rule.split(' contain ')[1]
- if inner_bag.strip() == 'no other':
- pass
- else:
- inner = []
- for color in inner_bag.split(', '):
- inner.append(color.split(" ", maxsplit = 1)[0])
- inner.append(color.split(" ", maxsplit = 1)[1])
- rules_2[outer_bag] = inner
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement