Ask Question
17 April, 02:38

Needed ingredients for recipes Before making a dish, we want to check whether we already have the necessary ingredients in our pantry or whether we need to go shopping. For this problem, you will implement a method needed_ingredients for the Pantry class. needed_ingredients takes a list of recipes as its argument and returns a new Pantry containing everything missing from our pantry to make all the recipes in the list. If our pantry already has all the necessary ingredients in the needed quantities, needed_ingredients returns an empty Pantry. There may be repeated recipes in the input list, and the input list may be empty. # You may wish to use defaultdict to implement needed_ingredients. from collections import defaultdict def needed_ingredients (self, recipes) : "Given a list of recipes, computes which ingredients to buy, and in which quantity, to be able to make all recipes. Can be implemented in 10 lines of code."* * #Code here raise Not ImplementedError ()

+4
Answers (1)
  1. 17 April, 04:20
    0
    See explaination

    Explanation:

    class Pantry (AD):

    def __init__ (self, ingredients):

    """ We initialize the Pantry class by passing the ingredients that were passed

    in to the initializer for the superclass AD"""

    super ().__init__ (ingredients)

    def needed_ingredients (self, recipes):

    """ Given a list of recipes, computes which ingredients to buy, and in which

    quantity to be able to make all recipes. Can be implemented in 10 lines of code."""

    # define the object new_pantry to contain the ingredients needed

    new_pantry = Pantry ({})

    ingredients_present = self

    # loop over the recipes in the list

    for recipe in recipes:

    # convert ingredients of recipe from AD to Pantry

    ingredients = Pantry (recipe. ingredients)

    # subtract the recipe's ingredients from ingredients_present

    ingredients_present = ingredients_present - ingredients

    # loop over the ingredients_present

    for key in ingredients_present:

    # if any ingredients's quantity < 0, add it to new_pantry

    if ingredients_present[key] < 0:

    # check if ingredient is present in new_pantry, add the quantity to existing quantity

    if key in new_pantry:

    new_pantry[key] + = - 1 * (ingredients_present[key])

    else: # if ingredient is not present in new_pantry, make a new entry for the ingredient

    new_pantry[key] = - 1 * (ingredients_present[key])

    ingredients_present[key] = 0 # set the quantity of the ingredient in ingredients_present to 0

    return new_pantry
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “Needed ingredients for recipes Before making a dish, we want to check whether we already have the necessary ingredients in our pantry or ...” in 📙 Computers & Technology if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers