aoc/07/07.py
2020-12-07 00:41:12 -06:00

58 lines
1.2 KiB
Python

def find_all_paths(graph, start, end, path =[]):
path = path + [start]
if start == end:
return [path]
if start == '':
return []
paths = []
for node in graph[start]:
if node not in path:
newpaths = find_all_paths(graph, node, end, path)
for newpath in newpaths:
paths.append(newpath)
return paths
with open("input.txt","r") as f:
rules = (f
.read()
.replace("bags","")
.replace("bag","")
.replace("no other","")
.replace(".","")
.replace(" ","")
.split('\n')
)
rules = [rule.split("contain") for rule in rules]
graph = {}
for rule in rules:
key = rule[0]
values = rule[1].split(',')
values = [value[1:] for value in values]
graph[key] = values
part1 = 0
for key in graph:
if key == "shinygold":
continue
if paths := find_all_paths(graph,key,"shinygold"):
part1 += 1
print(part1)
graph = {}
def numsplit(s):
if s == '':
return ('0', '')
return (s[0], s[1:])
for rule in rules:
key = rule[0]
values = rule[1].split(',')
values = [numsplit(value) for value in values]
graph[key] = values
def add_bags(key):
total = 0
if key == '':
return total
for num, color in graph[key]:
total += int(num) * (1 + add_bags(color))
return total
part2 = add_bags("shinygold")
print(part2)