#640 · Parsing · Advanced · Mini-project · 250 XP · about 100 min
Build a tool that rewrites a recipe for a different number of people, and in metric units if you like. A recipe is a list of ingredient lines such as '1 1/2 cups flour': an amount, an optional unit and the ingredient. Amounts are whole numbers (2), decimals (0.5), fractions (3/4) or a whole number and a fraction (1 1/2). The starter code gives you two tables: UNITS, every way a unit can be written mapped to its short name, and TO_METRIC, how many milliliters or grams one of each kitchen unit is.
parse_ingredient(line): return (amount, unit, name) with the amount as a float, the unit's short name from UNITS (the word after the amount, in any letter case), or '' when that word is not a unit, and the rest of the line as the name. '3 eggs' gives (3.0, '', 'eggs').scale(ingredients, serves, wanted): the recipe serves serves people and you want it for wanted. Return a new list with every amount multiplied by wanted / serves, and leave the original list as it was.to_metric(amount, unit): turn a kitchen unit (cup, tbsp, tsp, oz, lb) into milliliters or grams with TO_METRIC. Amounts in g or ml (converted or not) are then rounded with round() to a whole number, and 1,000 or more becomes kg or l (divided by 1,000). Return (amount, unit). Other units, and no unit, are returned as they are.format_amount(amount, unit): the amount as written on the card. g and ml as a whole number ('540'); kg and l with at most two decimals and no zeros at the end ('1.08', '1.5', '2'); anything else to the nearest quarter, round(amount * 4) quarters, as a whole number and a fraction ('2 1/4', '3/4', '3'). An amount too small to be a quarter is written '1/4', since the ingredient is still needed.recipe_card(lines, serves, wanted, metric): the whole job: parse every line, scale it, convert it with Part 3 when metric is True, and return the lines of the new card as 'amount unit name', or 'amount name' when there is no unit.parse_ingredient('1 1/2 cups flour') # returns (1.5, 'cup', 'flour') scale([(1.5, 'cup', 'flour'), (2.0, '', 'eggs')], 4, 6) # returns [(2.25, 'cup', 'flour'), (3.0, '', 'eggs')] to_metric(2.25, 'cup') # returns (540, 'ml') to_metric(5.0, 'lb') # returns (2.27, 'kg') format_amount(2.25, 'cup') # returns '2 1/4' recipe_card(['1 1/2 cups flour', '2 eggs', '1/2 tsp salt'], 4, 6, False) # returns ['2 1/4 cup flour', '3 eggs', '3/4 tsp salt']
Five pounds is 5 x 454 = 2,270 grams, which is 2.27 kilograms.
serves and wanted are whole numbers from 1 to 100.First solves only, ranked by stars and then time.