Skip to content

Instantly share code, notes, and snippets.

@sciyoshi
Created December 21, 2020 05:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sciyoshi/f42b3d3a8d30f1ff7b26b92189a3de00 to your computer and use it in GitHub Desktop.
Save sciyoshi/f42b3d3a8d30f1ff7b26b92189a3de00 to your computer and use it in GitHub Desktop.
import collections
all_ingredients = collections.Counter()
possible_ingredients = collections.defaultdict(set)
for line in open("inputs/day21").read().splitlines():
ingredients, allergens = line.rstrip(")").split(" (contains ")
ingredients = ingredients.split()
allergens = allergens.split(", ")
all_ingredients.update(ingredients)
for allergen in allergens:
if not possible_ingredients[allergen]:
possible_ingredients[allergen] = set(ingredients)
else:
possible_ingredients[allergen] &= set(ingredients)
fixed = {}
while possible_ingredients:
allergen, ingredients = min(possible_ingredients.items(), key=lambda el: len(el[1]))
fixed[allergen] = list(ingredients)[0]
for other in possible_ingredients.values():
other -= {fixed[allergen]}
del possible_ingredients[allergen]
print("part1:", sum(all_ingredients[i] for i in all_ingredients if i not in fixed.values()))
print("part2:", ",".join([ingredient for _, ingredient in sorted(fixed.items())]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment