Solving Linear Programming Problems with Python
Overview
You can use the scipy
package1. Input the linear programming problem expressed in matrix form, as in .
Code
As a simple example, let us solve the maximization problem in . At the shrimp sushi restaurant, this problem was solved manually using the simplex method, and the answer is known. This linear programming problem is
with , , , so it can be transcribed and solved as follows.
c = [-1, -1]
A = [[-1, 1], [1, 0], [0, 1]]
b = [1, 3, 2]
x1_bounds = (0, None)
x2_bounds = (0, None)
from scipy.optimize import linprog
res = linprog(c, A_ub=A, b_ub=b, bounds=[x1_bounds, x2_bounds])
The reason for using c = [-1,-1]
instead of c = [1,1]
is that linprog()
’s default optimization direction is for minimization. Just reversing that direction, the result is as we already knew, array([3., 2.])
.
>>> res
con: array([], dtype=float64)
fun: -4.99999999998958
message: 'Optimization terminated successfully.'
nit: 4
slack: array([2.00000000e+00, 2.76267897e-12, 7.65787433e-12])
status: 0
success: True
x: array([3., 2.])
Environment
- OS: Windows
- python: v3.9.7
- scipy v1.7.3