Skip to content

Instantly share code, notes, and snippets.

@schalla7
Created October 7, 2024 08:36
Show Gist options
  • Save schalla7/2c6f7b3388dc7f95569e38b9e8377d87 to your computer and use it in GitHub Desktop.
Save schalla7/2c6f7b3388dc7f95569e38b9e8377d87 to your computer and use it in GitHub Desktop.
python: use set(A) - set(B) to find items that are in A but not in B
#!/usr/bin/env python
# Given a list of ingredients needed for a recipe, represented as strings, and a list of ingredients you have in your pantry,
# write a function to return the minimum number of additional ingredients you need to buy to make the recipe.
# If you want to do some extra credit, add expiration dates to the pantry items, and only account for food that isn't expired.
# Example:
# Input:
# recipe = ["eggs", "flour", "sugar", "butter"]
# pantry = ["sugar", "butter", "milk"]
# Output:
# 2
# (you can submit your answers by replying to this email with a link to your solution, or share on LinkedIn, Twitter, Mastodon, or Bluesky)
def find_missing_ingredients(recipe, pantry):
# set(A) - set(B): Elements that are in A but not in B.
return len(set(recipe) - set(pantry))
if __name__ == "__main__":
cases = [
{
'recipe' : ["eggs", "flour", "sugar", "butter"],
'pantry' : ["sugar", "butter", "milk"],
'missing' : 2
},
{
'recipe' : ["water"],
'pantry' : [],
'missing' : 1
},
{
'recipe' : ["flour", "yeast", "salt"],
'pantry' : ["flour", "salt"],
'missing' : 1
},
{
'recipe' : ["eggs", "flour", "sugar", "butter", "milk"],
'pantry' : ["eggs", "flour", "sugar", "butter", "milk"],
'missing' : 0 # All ingredients present
},
{
'recipe' : ["tomato", "onion", "garlic", "basil"],
'pantry' : ["basil"],
'missing' : 3
},
{
'recipe' : [],
'pantry' : ["sugar", "butter"],
'missing' : 0 # No ingredients required for the recipe
},
{
'recipe' : ["cheese", "bread"],
'pantry' : ["cheese", "bread", "milk", "butter"],
'missing' : 0 # Extra pantry items, but no missing ingredients
},
{
'recipe' : ["salt", "pepper", "olive oil"],
'pantry' : ["salt", "pepper", "olive oil", "vinegar"],
'missing' : 0 # All ingredients are present, including extra pantry items
},
{
'recipe' : ["flour", "eggs", "sugar"],
'pantry' : ["sugar", "flour"],
'missing' : 1 # Missing eggs
},
{
'recipe' : ["chicken", "rice", "broth", "carrots"],
'pantry' : ["rice", "carrots"],
'missing' : 2 # Missing chicken and broth
},
]
for i, case in enumerate(cases):
recipe = case['recipe']
pantry = case['pantry']
expected_missing = case['missing']
actual_missing = find_missing_ingredients(recipe, pantry)
try:
assert actual_missing == expected_missing, \
f"Test case {i+1} failed: expected {expected_missing} missing ingredients but got {actual_missing}. Recipe: {recipe}, Pantry: {pantry}"
except AssertionError as e:
print(e)
else:
print(f"Test case {i+1} passed.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment