Decagon questions

Recipe Shopping Cart

DecagonPhone screenMedium

You are building RecipeCart for a cooking app. The constructor receives recipes, which maps each recipe name to its list of ingredients, and discounts, which maps each discounted ingredient to its tiers. A tier [threshold, amount] means the ingredient earns amount dollars off when at least threshold recipes in the cart use it. Among all tiers whose threshold is met, the highest threshold's amount applies. Ingredients not in discounts earn nothing. The cart holds at most one copy of each recipe and starts empty.

Part 1: Cart and bulk discounts

Implement add_recipe, remove_recipe, and get_total_discount.

add_recipe(recipe_name) puts the recipe in the cart if it is not already there; otherwise it does nothing. remove_recipe(recipe_name) takes the recipe out if it is present; otherwise it does nothing. Both methods return None.

get_total_discount() returns the total discount in dollars for the current cart. For each ingredient, count how many recipes in the cart use it. If that count meets one or more thresholds, the ingredient contributes the amount of the highest threshold met; otherwise it contributes 0. Sum these contributions. An empty cart has total discount 0.

  1. Example 1
    init
    [{"Aioli":["Garlic","Egg"],"Stir Fry":["Chicken","Garlic","Ginger"],"Chicken Parm":["Chicken","Garlic"],"Garlic Bread":["Bread","Garlic"]},{"Garlic":[[2,3],[4,8]]}]
    operations
    [["add_recipe",["Chicken Parm"]],["get_total_discount",[]],["add_recipe",["Stir Fry"]],["get_total_discount",[]],["add_recipe",["Garlic Bread"]],["get_total_discount",[]],["add_recipe",["Aioli"]],["get_total_discount",[]],["remove_recipe",["Stir Fry"]],["get_total_discount",[]]]
    Output
    [null,0,null,3,null,3,null,8,null,3]

    Why: After Chicken Parm, Garlic is used by one recipe, so no tier is met and the total is 0. Stir Fry raises Garlic's count to 2, meeting the [2, 3] tier. Garlic Bread raises it to 3, still $3. Aioli raises it to 4, meeting [4, 8]. Removing Stir Fry drops the count back to 3, so the total returns to $3.

Constraints

  • 1 <= len(recipes) <= 1000
  • Each value in recipes has between 1 and 20 distinct ingredients
  • Every recipe_name passed to a method is a key of recipes
  • Each tier list in discounts has between 1 and 5 tiers
  • Each tier list in discounts is sorted by increasing threshold
  • For every tier [threshold, amount], 1 <= threshold <= 1000
  • For every tier [threshold, amount], 1 <= amount <= 10^4
  • 1 <= len(operations) <= 10^4
  • Each operation is one of add_recipe, remove_recipe, get_total_discount
Import your own questions
Paste a question you were asked and get a full problem: statement, tests and a checked solution.
Import a question