108k views
0 votes
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. Hints: Pantry inherits the methods of its superclass, AD, so you can subtract one pantry from another. If you have an AD and need a Pantry, you can simply call the Pantry constructor on the AD.

User KoemsieLy
by
3.5k points

1 Answer

4 votes

Answer:

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

Step-by-step explanation:

I believe everything else is provided in the question.

Copy all the details you were provided in the question as it is and add the needed_ingredients in the Pantry class.

If you are getting any assertion error, Update the code to set the negative quantities in ingredients_present to 0

Before making a dish, we want to check whether we already have the necessary ingredients-example-1
User Mosi
by
3.1k points