Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Need some help with python problem: Given Codes: Problem: [] class AD (dict): def __init_(self, *args, **kwargs): This initializer simply passes all arguments to
Need some help with python problem:
Given Codes:
Problem:
[] class AD (dict): def __init_(self, *args, **kwargs): "" "This initializer simply passes all arguments to dict, so that we can create an AD with the same ease with which we can create a dict. There is no need, indeed, to repeat the initializer, but we leave it here in case we want to create attributes specific to an AD later." super(). __init__(*args, **kwargs) def _add_(self, other): return AD._binary op (self, other, lambda x, y: x + y, 0) def __sub_(self, other): return AD._binary_op(self, other, lambda x, y: x - y, 0) @staticmethod def _binary_op(left, right, op, neutral): r = AD() 1_keys = set(left. keys()) if isinstance(left, dict) else set() r_keys = set (right.keys()) if isinstance(right, dict) else set() for k in 1_keys r_keys: # If the right (or left) element is a dictionary (or an AD), # we get the elements from the dictionary; else we use the right # or left value itself. This implements a sort of dictionary # broadcasting. 1_val = left.get(k, neutral) if isinstance(left, dict) else left r_val = right.get(k, neutral) if isinstance(right, dict) else right r[k] = op(l_val, r_val) return r [] 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) class Recipe: def _init__(self, name, ingredients): """We initialize the Recipe class, which stores the name of a recipe as well as the needed ingredients in the form of an AD""" self.name = name self.ingredients = AD(ingredients) def _repr_(self): "To have a better representation of the recipe""" return f'{self.name}: {self.ingredients}' def_hash__(self): "Allows us to use a Recipe object inside a set or as a dictionary key. We assume that each recipe will have a unique name, and therefore we can simply use the built-in hash function on the name and return it as the hash id."" return hash(self.name) def _eq_(self,other): "'"For a recipe to equal another, their name and ingredients must match"" return self.name == other name and dict(self.ingredients) == dict(other.ingredients) To make sure everything is in order, we have some tests to ensure that our classes work. [] pantry = Pantry({"noodles":5, "soy sauce":8, "pepper":10, "bean sprouts":12, "egg":5, "lemon":6}) ramen = Recipe ("Ramen", {"noodles":1, "soy sauce":2, "egg": 2, "bean sprouts":4}) assert_equal(pantry, Pantry({"noodles":5, "soy sauce":8, "pepper":10, "bean sprouts":12, "egg":5, "lemon":6})) assert_equal(ramen.name, "Ramen") assert_equal(ramen.ingredients, AD({"noodles":1, "soy sauce":2, "egg":2, "bean sprouts":4})) Problem 1: 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. 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. [] # 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." # YOUR CODE HERE raise NotImplementedError() Pantry.needed_ingredients = needed_ingredients [ ] # Tests for Pantry.needed_ingredients pantry1 = Pantry({}) r1 = Recipe("r1", "egg":2, "beans":5}) r2 = Recipe("r2", {"egg":3, "rice":4}) r3 = Recipe("r3", "egg":4, "corn":1}) r4 = Recipe("r4", {"beans":5}) needed1 = pantryl.needed_ingredients([ri, r2, r3, 14]) assert_equal(needed1, {"egg": 9, "beans": 10, "rice": 4, "corn": 1)) assert isinstance (needed1, Pantry) needed2 = pantryl.needed_ingredients([r4, r4, r4, r4]) assert_equal(needed2, {"beans": 20}) assert isinstance (needed2, Pantry) pantry2 = Pantry({"noodles":5, "soy sauce":8, "pepper":10, "bean sprouts":12, "egg":5, "lemon":6}) ramen = Recipe("Ramen", {"noodles":1, "soy sauce":2, "egg": 2, "bean sprouts":4}) # We have enough in our pantry to make the ramen recipe once or twice... assert_equal(pantry2.needed_ingredients([ramen]), Pantry({})) assert_equal(pantry2.needed_ingredients([ramen, ramen]), Pantry({})) # ...but not three times or more. assert_equal (pantry2.needed_ingredients([ramen, ramen, ramen]), {"egg": 1}) assert_equal (pantry2.needed_ingredients([ramen, ramen, ramen, ramen]){"egg": 3, "bean sprouts":4}) [] class AD (dict): def __init_(self, *args, **kwargs): "" "This initializer simply passes all arguments to dict, so that we can create an AD with the same ease with which we can create a dict. There is no need, indeed, to repeat the initializer, but we leave it here in case we want to create attributes specific to an AD later." super(). __init__(*args, **kwargs) def _add_(self, other): return AD._binary op (self, other, lambda x, y: x + y, 0) def __sub_(self, other): return AD._binary_op(self, other, lambda x, y: x - y, 0) @staticmethod def _binary_op(left, right, op, neutral): r = AD() 1_keys = set(left. keys()) if isinstance(left, dict) else set() r_keys = set (right.keys()) if isinstance(right, dict) else set() for k in 1_keys r_keys: # If the right (or left) element is a dictionary (or an AD), # we get the elements from the dictionary; else we use the right # or left value itself. This implements a sort of dictionary # broadcasting. 1_val = left.get(k, neutral) if isinstance(left, dict) else left r_val = right.get(k, neutral) if isinstance(right, dict) else right r[k] = op(l_val, r_val) return r [] 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) class Recipe: def _init__(self, name, ingredients): """We initialize the Recipe class, which stores the name of a recipe as well as the needed ingredients in the form of an AD""" self.name = name self.ingredients = AD(ingredients) def _repr_(self): "To have a better representation of the recipe""" return f'{self.name}: {self.ingredients}' def_hash__(self): "Allows us to use a Recipe object inside a set or as a dictionary key. We assume that each recipe will have a unique name, and therefore we can simply use the built-in hash function on the name and return it as the hash id."" return hash(self.name) def _eq_(self,other): "'"For a recipe to equal another, their name and ingredients must match"" return self.name == other name and dict(self.ingredients) == dict(other.ingredients) To make sure everything is in order, we have some tests to ensure that our classes work. [] pantry = Pantry({"noodles":5, "soy sauce":8, "pepper":10, "bean sprouts":12, "egg":5, "lemon":6}) ramen = Recipe ("Ramen", {"noodles":1, "soy sauce":2, "egg": 2, "bean sprouts":4}) assert_equal(pantry, Pantry({"noodles":5, "soy sauce":8, "pepper":10, "bean sprouts":12, "egg":5, "lemon":6})) assert_equal(ramen.name, "Ramen") assert_equal(ramen.ingredients, AD({"noodles":1, "soy sauce":2, "egg":2, "bean sprouts":4})) Problem 1: 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. 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. [] # 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." # YOUR CODE HERE raise NotImplementedError() Pantry.needed_ingredients = needed_ingredients [ ] # Tests for Pantry.needed_ingredients pantry1 = Pantry({}) r1 = Recipe("r1", "egg":2, "beans":5}) r2 = Recipe("r2", {"egg":3, "rice":4}) r3 = Recipe("r3", "egg":4, "corn":1}) r4 = Recipe("r4", {"beans":5}) needed1 = pantryl.needed_ingredients([ri, r2, r3, 14]) assert_equal(needed1, {"egg": 9, "beans": 10, "rice": 4, "corn": 1)) assert isinstance (needed1, Pantry) needed2 = pantryl.needed_ingredients([r4, r4, r4, r4]) assert_equal(needed2, {"beans": 20}) assert isinstance (needed2, Pantry) pantry2 = Pantry({"noodles":5, "soy sauce":8, "pepper":10, "bean sprouts":12, "egg":5, "lemon":6}) ramen = Recipe("Ramen", {"noodles":1, "soy sauce":2, "egg": 2, "bean sprouts":4}) # We have enough in our pantry to make the ramen recipe once or twice... assert_equal(pantry2.needed_ingredients([ramen]), Pantry({})) assert_equal(pantry2.needed_ingredients([ramen, ramen]), Pantry({})) # ...but not three times or more. assert_equal (pantry2.needed_ingredients([ramen, ramen, ramen]), {"egg": 1}) assert_equal (pantry2.needed_ingredients([ramen, ramen, ramen, ramen]){"egg": 3, "bean sprouts":4})Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started