You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
47 lines
1.4 KiB
Python
47 lines
1.4 KiB
Python
4 years ago
|
"""Solution for 2020/21"""
|
||
|
|
||
|
from functools import reduce
|
||
|
|
||
|
foods = []
|
||
|
all_ingredients = set()
|
||
|
all_allergenes = set()
|
||
|
with open('input', 'r') as f:
|
||
|
for line in f.readlines():
|
||
|
[ing, alg] = line.strip(' \n)').split(' (contains ')
|
||
|
ing = set(ing.split(' '))
|
||
|
alg = set(alg.split(', '))
|
||
|
all_ingredients = all_ingredients.union(ing)
|
||
|
all_allergenes = all_allergenes.union(alg)
|
||
|
foods.append((ing, alg))
|
||
|
|
||
|
allergeneMap = {}
|
||
|
for ingredients, allergenes in foods:
|
||
|
for allergene in allergenes:
|
||
|
if allergene not in allergeneMap:
|
||
|
allergeneMap[allergene] = ingredients
|
||
|
else:
|
||
|
allergeneMap[allergene] = allergeneMap[allergene].intersection(
|
||
|
ingredients)
|
||
|
print(f'{allergeneMap=}')
|
||
|
|
||
|
allergenic = reduce(lambda x, y: x.union(y), allergeneMap.values())
|
||
|
|
||
|
unallergenic = all_ingredients.difference(allergenic)
|
||
|
print(f'{allergenic=}')
|
||
|
print(f'{unallergenic=}')
|
||
|
|
||
|
ingredientMap = {}
|
||
|
processed = set()
|
||
|
while len(processed) < len(allergenic):
|
||
|
for allergene, ingredients in allergeneMap.items():
|
||
|
reduced_ing = ingredients.difference(processed)
|
||
|
if len(reduced_ing) == 1:
|
||
|
ing = reduced_ing.pop()
|
||
|
processed.add(ing)
|
||
|
ingredientMap[ing] = allergene
|
||
|
|
||
|
print(f'{ingredientMap=}')
|
||
|
|
||
|
sorted_items = sorted(ingredientMap.items(), key=lambda x: x[1])
|
||
|
print(','.join(map(lambda x: x[0], sorted_items)))
|