Scale Serving Sizes in a Shopping List
StringsAuto-graded · 20 test casesLast updated
Tests careful string parsing: multiply only the leading numeric token in each line while leaving the rest of the text exactly as-is.
You have a shopping list written for a single person. Each line starts with a whole number representing how much of that item is needed, followed by exactly one space, then a description of the item.
Given the number of people to serve (nb_persons) and the list of ingredient lines, return a new list where every leading quantity has been multiplied by nb_persons. Everything else — the description text, its spacing, its punctuation, and any digits that appear inside it — must be carried over without modification.
Do not adjust singular or plural wording in the description. The multiplied quantity should be written as ordinary decimal digits with no leading zeros.
How Each Line Is Structured
<quantity> <description>
<quantity>— a positive integer, the first token on the line (before the first space).<description>— everything after that first space, which may itself contain digits, spaces, or special characters. Treat it as opaque text.
Constraints
1 <= nb_persons <= 1 000 0000 <= len(ingredients) <= 10 000- Each leading quantity is a decimal integer between
1and1 000 000inclusive. - The description that follows is non-empty and contains at most 200 ASCII characters.
- Every character after the first space belongs to the description and must be preserved exactly.
- The maximum possible product (
1 000 000 × 1 000 000 = 10^12) exceeds a signed 32-bit integer — use a type or language feature that handles this.
Examples
Example 1
Input: scale_ingredient_amounts(3, ['2 eggs', '200 grams of flour', '150 grams of sugar', '1 liter(s) of milk'])
Output: ['6 eggs', '600 grams of flour', '450 grams of sugar', '3 liter(s) of milk']
Example 2
Input: scale_ingredient_amounts(4, ['2 packs of 6 rolls', '1 bottle of 2 percent milk'])
Output: ['8 packs of 6 rolls', '4 bottle of 2 percent milk']
Hints
Hint 1
The only number you should multiply is the one that comes before the very first space on each line. Any digits elsewhere are part of the item description and must not change.
Hint 2
Split each line at the first space only — not at every space. In Python, `str.split(' ', 1)` does exactly this: it gives you two parts and stops after the first split, so the rest of the description is untouched regardless of what it contains.
Hint 3
After scaling the leading number, reconstruct the line by joining the new quantity, a single space, and the original description string. Avoid using replace() or a regex that matches all digit runs — those approaches would also alter numbers embedded in the description.
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Every line has a predictable structure: a numeric token, one space, then free-form text. The task is purely about position — only the token that sits before the very first space is a quantity. Everything after that boundary is description and must be returned byte-for-byte unchanged.
The algorithm for each line:
- Split at the first space only, producing exactly two parts: the numeric prefix and the remainder.
- Convert the prefix to an integer and multiply by
nb_persons. - Concatenate the new number, a single space, and the unmodified description.
Return the results in the same order as the input.
Why This Is Correct
Only the leading token is scaled. Using split(" ", 1) with maxsplit=1 ensures the split stops after the first space. The description — including any digits, extra spaces, or punctuation it contains — lands in one piece as the second element and is never inspected or altered.
The description is preserved exactly. Because maxsplit=1 performs no further splitting, internal spaces are not collapsed, trailing characters are not trimmed, and embedded numbers like the 6 in "packs of 6 rolls" or the 2 in "2 percent milk" pass through unchanged.
No overflow. The largest possible product is 1 000 000 × 1 000 000 = 10^12, which exceeds the range of a signed 32-bit integer. Python's arbitrary-precision integers handle this without any special handling. In a statically typed language you would need a 64-bit type (long in Java, long long in C++).
Output format. Formatting with an f-string produces plain decimal digits. A quirky input like "007 eggs" becomes "14 eggs" when nb_persons = 2 — the leading zeros in the original quantity are not reproduced.
Common Pitfalls
split()with no arguments splits on every run of whitespace and discards it, so rejoining produces incorrect spacing in the description.- Regex over the whole line — for example
re.sub(r"\d+", ...)— will also transform numbers inside the description, which the problem explicitly forbids. str.replace(old, new)without a count of 1 rewrites every occurrence of the numeric prefix throughout the line. Even with a count of 1 it is fragile; a clean split is clearer and unambiguous.- Pluralizing the description — the contract says not to touch wording, so
"4 bottle of 2 percent milk"is the correct output even though it sounds ungrammatical.
Complexity
- Time: O(L), where L is the total number of characters across all lines. Each line is scanned once to locate the first space and then copied once into the output.
- Space: O(L) for the output list. Only O(1) additional bookkeeping is needed per line.
Edge Cases
| Situation | Input (×4) | Expected output |
|---|---|---|
| Empty list | [] | [] |
| Digit in description | "2 packs of 6 rolls" | "8 packs of 6 rolls" |
| Description echoes the quantity | "2 packs of 2 rolls" | "8 packs of 2 rolls" |
| Extra / trailing spaces | "1 cup of rice " | "4 cup of rice " |
nb_persons = 1 | "5 eggs" | "5 eggs" |
| Leading zeros in input | "007 eggs" (×2) | "14 eggs" |
| Maximum values | "1000000 g" (×1 000 000) | "1000000000000 g" |
Reference Solution
from typing import List
def scale_ingredient_amounts(nb_persons: int, ingredients: List[str]) -> List[str]:
result = []
for ingredient in ingredients:
# Split only at the first space so the description is never touched.
quantity, description = ingredient.split(" ", 1)
# Python ints are arbitrary-precision, so products beyond 32 bits are fine.
result.append(f"{int(quantity) * nb_persons} {description}")
return result