(Integer) Linear Programming in Python

Step one:

brew install glpk
pip install pulp

Step two:

from pulp import * 
 
prob = LpProblem("test1", LpMinimize) 
 
# Variables 
x = LpVariable("x", 0, 4, cat="Integer") 
y = LpVariable("y", -1, 1, cat="Integer") 
z = LpVariable("z", 0, cat="Integer") 
 
# Objective 
prob += x + 4*y + 9*z 
 
# Constraints 
prob += x+y <= 5 
prob += x+z >= 10 
prob += -y+z == 7 
 
GLPK().solve(prob) 
 
# Solution 
for v in prob.variables():
    print v.name, "=", v.varValue 
 
print "objective=", value(prob.objective)

In the documentation there are further examples, e.g. one to minimise the cost of producing cat food.

Leave a Reply