DEV Community


Advent of Code 2020: Python Solution Day 21

Passionate ML and Game Dev learner from Nepal who loves sharing what he knows via blogging.
・1 min read

Today's challenge was very easy but was pretty tricky to tackle. I found the solution to first part by using python sets and for the second part, I used help from Reddit.

Please share your solution too.

with open("day21.txt") as fp:
    lines =

food_dict = {}
safe_ingredient = set()
all_ingredients = []
for food in lines:
    ingredients, allergens = food.split(" (contains ")
    allergens = allergens[:-1]
    ingredients = ingredients.split(" ")
    unique_in = set(ingredients)
    allergens = allergens.split(", ")

    for allergen in allergens:
        if food_dict.get(allergen) is None:
            food_dict[allergen] = unique_in
            food_dict[allergen] = food_dict[allergen].intersection(unique_in)

safe_ingredient = safe_ingredient.difference(set(k for value in food_dict.values() for k in value))
safe_count = sum([ingredient in safe_ingredient for ingredient in all_ingredients])
print(f"Safe ingredients: {safe_count}")

while any([len(i) > 1 for i in food_dict.values()]):    
    for a, i in food_dict.items():                      
        if len(i) == 1:                                 
            alg = list(i)[0]                            
            for a2, i2 in food_dict.items():            
                if a2 == a:                             
                if len(i2) > 1:                         
                    if alg in i2:                       

names = list(food_dict.keys())                          
print("My dangerous list: ", ",".join([",".join(food_dict[i]) for i in names]))
Enter fullscreen mode Exit fullscreen mode

Discussion (0)