Skip to content

Instantly share code, notes, and snippets.

@yoojinl
Created January 1, 2016 11:42
Show Gist options
  • Save yoojinl/0dd0827504d42a33c229 to your computer and use it in GitHub Desktop.
Save yoojinl/0dd0827504d42a33c229 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
from pulp import *
import sys
x = []
thismodule = sys.modules[__name__]
for i in range(8):
name = 'x{0}'.format(i)
var = LpVariable(name, 0, None)
setattr(thismodule, name, var)
x.append(var)
# defines the problem
prob = LpProblem("problem", LpMinimize)
# defines the constraints
prob += (+1.0 * x0) + (+1.0 * x1) + (+1.0 * x2) + (+1.0 * x3) + (+0.0 * x4) + (+0.0 * x5) + (+0.0 * x6) + (+0.0 * x7) == 40
prob += (+0.0 * x0) + (+0.0 * x1) + (+0.0 * x2) + (+0.0 * x3) + (+1.0 * x4) + (+1.0 * x5) + (+1.0 * x6) + (+1.0 * x7) == 40
prob += (+0.0 * x0) + (+1.0 * x1) + (-1.0 * x2) + (+0.0 * x3) + (+0.0 * x4) + (+1.0 * x5) + (-1.0 * x6) + (+0.0 * x7) == 0
prob += (+1.0 * x0) + (+0.0 * x1) + (+0.0 * x2) + (+0.0 * x3) + (+1.0 * x4) + (+0.0 * x5) + (+0.0 * x6) + (+0.0 * x7) <= 20
prob += (-1.0 * x0) + (-0.0 * x1) + (-0.0 * x2) + (-0.0 * x3) + (-1.0 * x4) + (-0.0 * x5) + (-0.0 * x6) + (-0.0 * x7) <= -10
prob += (-0.0 * x0) + (-1.0 * x1) + (-0.0 * x2) + (-0.0 * x3) + (-0.0 * x4) + (-1.0 * x5) + (-0.0 * x6) + (-0.0 * x7) <= 0
prob += (-0.0 * x0) + (-0.0 * x1) + (-1.0 * x2) + (-0.0 * x3) + (-0.0 * x4) + (-0.0 * x5) + (-1.0 * x6) + (-0.0 * x7) <= 0
prob += (-0.0 * x0) + (-0.0 * x1) + (-0.0 * x2) + (-1.0 * x3) + (-0.0 * x4) + (-0.0 * x5) + (-0.0 * x6) + (-1.0 * x7) <= 0
for i in x:
prob += i >= 0
# defines the objective function to maximize
prob += (-8 * x0) + (+0 * x1) + (+0 * x2) + (-1 * x3) + \
(-4 * x4) + (-6 * x5) + (-4 * x6) + (-1 * x7)
# solve the problem
status = prob.solve(GLPK(msg=0))
# print the results x1 = 20, x2 = 60
print '\n'.join(['x_{0} = {1}'.format(i, value(v)) for i, v in enumerate(x)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment