Scale Ingredient Quantities
UpstartSoftware Engineer · Online AssessmentLast updated
This problem tests string parsing and manipulation, specifically isolating numeric prefixes from measurement units and descriptive text while maintaining the relative structure of ingredient lists.
Scaling Ingredients
You are building a feature for a recipe app that allows users to adjust serving sizes. You are given a list of strings, where each string represents an ingredient in the format: "[quantity] [unit] [name]".
Write a function scale_ingredients(ingredients, servings) that returns a new list of strings where the quantity of each ingredient has been multiplied by the servings factor.
Requirements:
- The
quantitywill always be the first integer in the string. - The
unitandnameshould remain unchanged. - If
servingsis 0, the output should reflect a quantity of 0 for all ingredients. - The function must preserve the original order of the input list.
Function Signature
def scale_ingredients(ingredients: list[str], servings: int) -> list[str]
Examples
Example 1:
Input: ingredients = ["2 cups flour", "1 tbsp salt"], servings = 3
Output: ["6 cups flour", "3 tbsp salt"]
Example 2:
Input: ingredients = ["10 grams sugar"], servings = 0
Output: ["0 grams sugar"]
Constraints
ingredientscontains between 1 and 100 strings.quantitywill always be a positive integer in the input.- The format "[quantity] [unit] [name]" is guaranteed for every input string.
servingswill be an integer between 0 and 1000.
Edge Cases
- Consider inputs where
servingsis 0 or 1. - Ensure multi-word names (e.g., "extra virgin olive oil") are preserved correctly.
Hints
Hint 1
Use the string split method to isolate the first part of the string, which contains the quantity.
Hint 2
Convert the first substring into an integer, multiply it by the servings variable, and then join it back with the remainder of the original string.
Hint 3
The string method `split(maxsplit=1)` is useful for separating the quantity from the rest of the string description.
Follow-up questions
- How would you modify your solution if the input format allowed for optional units (e.g., '2 eggs' instead of '2 units eggs')?
- What if the input could contain floating-point quantities instead of integers?
- How would you handle potential input validation errors if an ingredient string does not match the expected format?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.