Try our new documentation site (beta).


# Copyright 2016, Gurobi Optimization, Inc.

# Solve the classic diet model.  This file implements
# a function that formulates and solves the model,
# but it contains no model data.  The data is
# passed in by the calling program.  Run example '',
# '', or '' to invoke this function.

from gurobipy import *

def solve(categories, minNutrition, maxNutrition, foods, cost,
    # Model
    m = Model("diet")

    # Create decision variables for the nutrition information,
    # which we limit via bounds
    nutrition = {}
    for c in categories:
        nutrition[c] = m.addVar(lb=minNutrition[c], ub=maxNutrition[c], name=c)

    # Create decision variables for the foods to buy
    buy = {}
    for f in foods:
        buy[f] = m.addVar(obj=cost[f], name=f)

    # The objective is to minimize the costs
    m.modelSense = GRB.MINIMIZE

    # Update model to integrate new variables

    # Nutrition constraints
    for c in categories:
          quicksum(nutritionValues[f,c] * buy[f] for f in foods) ==
                    nutrition[c], c)

    def printSolution():
        if m.status == GRB.Status.OPTIMAL:
            print('\nCost: %g' % m.objVal)
            for f in foods:
                if buy[f].x > 0.0001:
                    print('%s %g' % (f, buy[f].x))
            for c in categories:
                print('%s %g' % (c, nutrition[c].x))
            print('No solution')

    # Solve

    print('\nAdding constraint: at most 6 servings of dairy')
    m.addConstr(buy['milk'] + buy['ice cream'] <= 6, "limit_dairy")

    # Solve

Try Gurobi for Free

Choose the evaluation license that fits you best, and start working with our Expert Team for technical guidance and support.

Evaluation License
Get a free, full-featured license of the Gurobi Optimizer to experience the performance, support, benchmarking and tuning services we provide as part of our product offering.
Academic License
Gurobi supports the teaching and use of optimization within academic institutions. We offer free, full-featured copies of Gurobi for use in class, and for research.
Cloud Trial

Request free trial hours, so you can see how quickly and easily a model can be solved on the cloud.