Solve the diet problem in Python

The diet problem — choose how much of each food to buy so a set of nutrient requirements is met at minimum cost — is the problem that motivated early linear programming (Stigler, 1945) and still the cleanest way to learn LP. With quicopt it is a few lines in Python.

The naive approach

The tempting shortcut is to greedily pick the cheapest food per nutrient, or to try combinations by hand. Because each food contributes to several nutrients at once, that misses the cheapest balanced mix. The problem is linear — solve it exactly.

Model it as an LP

A continuous variable per food is the quantity to buy. One constraint per nutrient enforces its minimum, and the objective minimizes total cost:

diet.py
from ortools.math_opt.python import mathopt
from quicopt import Client

# Choose food quantities meeting nutrient minimums at minimum cost.
cost    = [2.0, 3.5, 1.5, 4.0]
protein = [4.0, 6.0, 3.0, 8.0]
iron    = [2.0, 1.0, 4.0, 3.0]
N = len(cost)

model = mathopt.Model(name="diet")
x = [model.add_variable(lb=0.0, name=f"food_{i}") for i in range(N)]
model.add_linear_constraint(sum(protein[i] * x[i] for i in range(N)) >= 20.0)
model.add_linear_constraint(sum(iron[i] * x[i] for i in range(N)) >= 10.0)
model.minimize(sum(cost[i] * x[i] for i in range(N)))

client = Client("https://try.quicoptapi.pgi.fz-juelich.de")
print(client.solve(model).display)
$ python diet.py
├── status:     optimal
├── feasible:   true
├── objective:  10.0
├── x:          food_0=5, food_1=0, food_2=0, food_3=0  (4 variables)
└── solve_time: 0.0023 s

What you get

status: optimal means the plan is proven cheapest — cost 10.0, meeting both the protein (≥20) and iron (≥10) minimums, in a couple of milliseconds.

The same model scales to hundreds of foods and dozens of nutrients — you change the data, not the method. (An illustrative optimization example, not nutritional advice.)

Next

Reference: G. J. Stigler, The Cost of Subsistence, Journal of Farm Economics, 1945.

A bigger nutrition model — or a different problem?

Tell us what you're optimizing. We'll help you model it and point you at the right approach.

Talk to us →

Frequently asked questions

Why not just pick the cheapest food that covers each nutrient?

Foods contribute to several nutrients at once, so a greedy pick over- or under-shoots and costs more. The LP balances all nutrients simultaneously at minimum cost.

Can I add upper bounds or variety constraints?

Yes — maximum servings, calorie caps, or 'at least k foods' are extra linear constraints on the same model.

Is quicopt free to use?

Yes — pip install quicopt and your first call sets up a free key, no license.