Last active
April 22, 2025 13:46
-
-
Save kracekumar/e6ed094a6dc6e311920707beca68c696 to your computer and use it in GitHub Desktop.
Given an array of objects representing ingredients (each with a name and amount per serving), and a target number of servings, write a function to calculate the required amount of each ingredient for the target servings. Return the results as an array of objects with name and amount. Can you do this in less than 5 lines? In one?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Given an array of objects representing ingredients (each with a name and amount per serving), and a target number of servings, write a function to calculate the required amount of each ingredient for the target servings. Return the results as an array of objects with name and amount. Can you do this in less than 5 lines? In one? | |
Example: | |
const ingredients = [ | |
{ name: "flour", amount: 200 }, // 200g per | |
{ name: "sugar", amount: 100 }, // 100g per | |
{ name: "eggs", amount: 2 } // 2 eggs per | |
]; | |
const targetServings = 3; | |
> calculateIngredients(ingredients, targetServings); | |
> [ | |
{ name: "flour", amount: 600 }, | |
{ name: "sugar", amount: 300 }, | |
{ name: "eggs", amount: 6 } | |
] | |
""" | |
def calculateIngredients(ingredients, targetServings): | |
return [{key: (val * targetServings if isinstance(val, (int, float)) else val * targetServings) | |
for key, val in ingredient.items()} for ingredient in ingredients] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment