# PuLP—整数规划例子

m a x x + y + 2 z s . t . x + 2 y + 3 z ≤ 4 x + y ≥ 1 x , y , z b i n a r y \begin{aligned} &amp; max &amp; \quad x+y+2z \\ &amp; \\ &amp; s.t. \quad &amp; x+2y+3z \le 4 \\ &amp; \quad &amp; x+y \ge 1 \\ &amp; \quad &amp; x,y,z \quad binary \end{aligned}

## 实现

Python代码：

# coding=utf-8

from pulp import LpProblem, LpVariable, LpConstraint, LpConstraintLE, LpConstraintGE, LpMaximize, LpBinary, LpStatus

# Create a new model
m = LpProblem(name="MIP Model", sense=LpMaximize)

# Create variables
x = LpVariable(cat=LpBinary, name="x")
y = LpVariable(cat=LpBinary, name="y")
z = LpVariable(cat=LpBinary, name="z")

# Add constraint: x + 2 y + 3 z <= 4
m += LpConstraint(e=(x + 2 * y + 3 * z), sense=LpConstraintLE, rhs=4, name='c0')

# Add constraint: x + y >= 1
m += LpConstraint(e=(x + y), sense=LpConstraintGE, rhs=1, name='c1')

# Set objective
m.setObjective(x + y + 2 * z)

# Calculate with the default CBC optimizer
status = m.solve()

if LpStatus[status] == 'Optimal':

for v in m.variables():
print('%s %g' % (v.name, v.varValue))

print('Obj: %g' % m.objective.value())


x 1
y 0
z 1
Obj: 3


## Bonus

# Add constraint: x + 2 y + 3 z <= 4
m += x + 2 * y + 3 * z <= 4, 'c0'

# Add constraint: x + y >= 1
m += x + y >= 1, 'c1'

# Set objective
m += x + y + 2 * z, 'Obj'


PuLP默认使用CBC优化器，如果想用其它的优化器：

from pulp.solvers import CPLEX, GUROBI

# Calculate with CPLEX or GUROBI
m.solve(solver=CPLEX())


04-02 4617

10-11 7854
04-06 5359
04-07 548
08-26 2644
05-17 1万+
09-10 1万+
02-06 1万+
05-07 1827
04-07 2255
08-19 8469
09-04 1万+
11-20 2011
01-12 485
05-09 6212
08-07 4543