1. Mixed Integer Programming
Easy
Description
Formulate and solve the following simple MIP model:
🚀 Test your code
Try to solve the problem below in the code editor before reading the solution.
Solutions
import gurobipy as gp
from gurobipy import GRB
# Create a new model
m = gp.Model("mip1")
# Create variables
x = m.addVar(vtype=GRB.BINARY, name="x")
y = m.addVar(vtype=GRB.BINARY, name="y")
z = m.addVar(vtype=GRB.BINARY, name="z")
# Set objective
m.setObjective(x + y + 2 * z, GRB.MAXIMIZE)
# Add constraint: x + 2 y + 3 z <= 4
m.addConstr(x + 2 * y + 3 * z <= 4, "c0")
# Add constraint: x + y >= 1
m.addConstr(x + y >= 1, "c1")
# Optimize model
m.optimize()
for v in m.getVars():
print(f"{v.VarName} {v.X:g}")
print(f"Obj: {m.ObjVal:g}")
from pulp import *
def solve_mip_model():
# Create the model
model = LpProblem(name="maximize_xyz", sense=LpMaximize)
# Define the decision variables
x = LpVariable(name="x", cat=LpBinary)
y = LpVariable(name="y", cat=LpBinary)
z = LpVariable(name="z", cat=LpBinary)
# Add the objective function
model += lpSum([x, y, 2*z]), "objective_function"
# Add the constraints
model += (x + 2*y + 3*z <= 4), "constraint_1"
model += (x + y >= 1), "constraint_2"
# Solve the model
model.solve()
# Print the results
print(f"Status: {model.status}")
print(f"Objective value: {model.objective.value()}")
for var in model.variables():
print(f"{var.name}: {var.value()}")
if __name__ == "__main__":
solve_mip_model()