Best Value on the Shelf

Data with PythonMedium+10 XP+10

Best Value on the Shelf

Supermarket packs come in different sizes, so the price on the label doesn't tell you which is the best deal. Comparing the price per 100 g does.

Task: write best_value(packs, k) that returns the k best-value packs.

  • packs is a list of dictionaries, each with name, price (in pounds) and grams.
  • Work out each pack's price per 100 g: price ÷ grams × 100.
  • The best value is the lowest price per 100 g.
  • Return a list of [name, price per 100 g] pairs, best value first, with each price per 100 g rounded to 2 decimal places.
  • If k is bigger than the number of packs, return all of them.
  • No two packs have the same price per 100 g.

Examples

packs = [{"name": "oats small", "price": 1.2, "grams": 500}, {"name": "oats big", "price": 2.0, "grams": 1000}, {"name": "oats posh", "price": 2.5, "grams": 750}]
k = 2
returns [['oats big', 0.2], ['oats small', 0.24]]
packs = [{"name": "rice A", "price": 3.4, "grams": 2000}, {"name": "rice B", "price": 1.1, "grams": 500}, {"name": "rice C", "price": 0.75, "grams": 250}, {"name": "rice D", "price": 6.0, "grams": 5000}]
k = 1
returns [['rice D', 0.12]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run