#!/usr/bin/env python3
#Advent of Code
#2020 Day 21, Part 1
#Solution by James C. (https://github.com/JamesMCo)
importos,syssys.path.append(os.path.abspath("../.."))importunittest,util.readfromutil.testsimportrundefsolve(puzzle_input):# Based partly on a hint that was given to me by a friend (whose solution repo
# can be found here: https://gitlab.com/Nohus/advent-of-code-2020/-/tree/master )
# He suggested that I map from allergens to ingredients, rather than what I had
# originally (ingredients to allergens)
defparse(food):food=food[:-1].split(" (contains ")return (food[0].split(),food[1].split(", "))foods=[parse(food)forfoodinpuzzle_input]all_ingredients=set.union({xforfoodinfoodsforxinfood[0]})all_allergens=set.union({xforfoodinfoodsforxinfood[1]})a_to_ing_opts={a:all_ingredientsforainall_allergens}foringredients,allergensinfoods:forallergeninallergens:a_to_ing_opts[allergen]=a_to_ing_opts[allergen].intersection(set(ingredients))maybe_has_allergen=set.union(*list(a_to_ing_opts.values()))cant_have_allergen=all_ingredients.difference(maybe_has_allergen)original_ingredients=[xforfoodinfoodsforxinfood[0]]returnsum(original_ingredients.count(ingredient)foringredientincant_have_allergen)defmain():puzzle_input=util.read.as_lines()ingredient_count=solve(puzzle_input)print("The number of times ingredients with no allergens appear is "+str(ingredient_count)+".")classAOC_Tests(unittest.TestCase):deftest_ex1(self):returnself.assertEqual(solve(["mxmxvkd kfcds sqjhc nhms (contains dairy, fish)","trh fvjkl sbzzf mxmxvkd (contains dairy)","sqjhc fvjkl (contains soy)","sqjhc mxmxvkd sbzzf (contains fish)"]),5)if__name__=="__main__":run(main)