Skip to content

Instantly share code, notes, and snippets.

@vinovator
Last active March 24, 2022 18:38
Show Gist options
  • Save vinovator/b1db818c7c943a347e0e to your computer and use it in GitHub Desktop.
Save vinovator/b1db818c7c943a347e0e to your computer and use it in GitHub Desktop.
Python script to solve Linear Programming problems using PuLP library
# simpleLP1.py
# Python 2.7.6
"""
Python script to solve Linear Programming problems
Uses Pulp library
Problem statement: (src - http://fisher.osu.edu/~croxton.4/tutorial/)
1) Objective Function -
mathematical expression of what we are trying to accomplish
For eg. If you are producing 3 products P1, P2 and P3 each selling
for 2$, 3$ and 8$ respectively.
And if your objective is to maximise profit, then objective function is,
Objective Function >> Maximise 2P1 + 3P2 + 8P3
2) Constraints - Linear expression which restricts our variables.
"Constraint sense" could be =<, >=, or =
Strict inequalities such as < or > cannot be used
"RHS" Right hand side - limiting value of expression
For eg,
a. if we have a total production cost budget as $300 and the
production cost of P1, P2, P3 are $1, $2 and $5 respectively
b. Product P1 and product P2 should be made in a combination of
atleast 50 units
c. Product P1 takes 2 hours to produce and similarly product P2
takes 4 hours and Product P3 takes 5 hours and the total production
time is exactly 400 hours
Constraints >>
1P1 + 2P2 + 5P3 <= 300
1P1 + 1P2 >= 50
2P1 + 4P2 + 5P3 = 400
3) Sign Restrictions - additional constraints, which are often forgotten
e.g. The number of products cannot be negative, so
P1 >= 0
P2 >= 0
P3 >= 0
"""
import pulp as p
# declare all variables
P1 = p.LpVariable("P1", 0) # P1 >= 0
P2 = p.LpVariable("P2", 0) # P2 >= 0
P3 = p.LpVariable("P3", 0) # P3 >= 0
# define the problem
prob = p.LpProblem("problem", p.LpMaximize)
# define the constraints
prob += 1 * P1 + 2 * P2 + 5 * P3 <= 300
prob += 1 * P1 + 1 * P2 >= 50
prob += 2 * P1 + 4 * P2 + 5 * P3 == 400
prob += P1 >= 0
prob += P2 >= 0
prob += P3 >= 0
# Define the objective function to maximize
# Objective here is to maximize profits
prob += 2 * P1 + 3 * P2 + 8 * P3
# Solve the problem
status = prob.solve()
print("This is the {} solution".format(p.LpStatus[status]))
# make sure we got an optimal solution
assert status == p.LpStatusOptimal
# print the value of P1, P2 and P3
print("To maximize profitability you have to sell {} P1, {} P2 and {} P3".
format(p.value(P1), p.value(P2), p.value(P3)))
print("The maximum profit to be derived is $ {}".format(
prob.objective.value()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment