2020/python/day21.py

44 lines
1.3 KiB
Python

import fileinput
from pprint import pprint
# Parse the input
foods = []
all_allergens = set()
all_ingredients = set()
for line in fileinput.input():
line = line.strip().rstrip(")")
s = line.split(" (contains ")
ingredients = frozenset(s[0].split())
allergens = frozenset(s[1].split(", "))
all_allergens.update(allergens)
all_ingredients.update(ingredients)
foods.append((ingredients, allergens))
allergen_ingredients = {allergen: set(all_ingredients) for allergen in all_allergens}
for ingredients, allergens in foods:
for allergen in allergens:
allergen_ingredients[allergen] &= ingredients
visited_ingredients = set()
for allergen, ingredients in sorted(
allergen_ingredients.items(), key=lambda x: len(x[1])
):
ingredients -= visited_ingredients
visited_ingredients |= ingredients
safe_ingredients = set(all_ingredients)
for _, ingredients in allergen_ingredients.items():
safe_ingredients -= ingredients
part1 = 0
for ingredient in safe_ingredients:
part1 += sum((ingredient in ingredients) for ingredients, _ in foods)
print("part 1:", part1)
dangerous_ingredients = []
for allergen, ingredients in sorted(allergen_ingredients.items(), key=lambda x: x[0]):
dangerous_ingredients.extend(ingredients)
print("part 2:", ",".join(dangerous_ingredients))