#!/usr/bin/env python3# Copyright 2025, Gurobi Optimization, LLC# This example formulates and solves the following simple MIP model:# maximize# x + y + 2 z# subject to# x + 2 y + 3 z <= 4# x + y >= 1# x, y, z binaryimportgurobipyasgpfromgurobipyimportGRBtry:# Create a new modelm=gp.Model("mip1")# Create variablesx=m.addVar(vtype=GRB.BINARY,name="x")y=m.addVar(vtype=GRB.BINARY,name="y")z=m.addVar(vtype=GRB.BINARY,name="z")# Set objectivem.setObjective(x+y+2*z,GRB.MAXIMIZE)# Add constraint: x + 2 y + 3 z <= 4m.addConstr(x+2*y+3*z<=4,"c0")# Add constraint: x + y >= 1m.addConstr(x+y>=1,"c1")# Optimize modelm.optimize()forvinm.getVars():print(f"{v.VarName}{v.X:g}")print(f"Obj:{m.ObjVal:g}")exceptgp.GurobiErrorase:print(f"Error code{e.errno}:{e}")exceptAttributeError:print("Encountered an attribute error")
Help and Feedback