From cc5bbc726002fce4fd51b0a7eb3a063adb360ae6 Mon Sep 17 00:00:00 2001 From: Sijmen Schoon Date: Thu, 24 Dec 2020 02:27:59 +0100 Subject: [PATCH] python(day21): Day 21 woo --- python/day21.py | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 python/day21.py diff --git a/python/day21.py b/python/day21.py new file mode 100644 index 0000000..d2157e5 --- /dev/null +++ b/python/day21.py @@ -0,0 +1,43 @@ +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))