How to Solve Linear Programming (LP) Problems Using Python

Hello everyone and welcome! In this post, I’m going to show you how to solve linear programming problems using Python. It is very easy and very effective. A transshipment problem will be used to demonstrate this method.

Here are the details of the transshipment problem to be solved.

Here are the details of the math model of the transshipment problem.

Let’s see how it works:

For more videos like this, check my YouTube channel here.

Python code

from pulp import *

# variables
x1 = LpVariable('x1', lowBound=0, cat='Integer')
x2 = LpVariable('x2', lowBound=0, cat='Integer')
x3 = LpVariable('x3', lowBound=0, cat='Integer')
x4 = LpVariable('x4', lowBound=0, cat='Integer')
x5 = LpVariable('x5', lowBound=0, cat='Integer')
x6 = LpVariable('x6', lowBound=0, cat='Integer')
x7 = LpVariable('x7', lowBound=0, cat='Integer')
x8 = LpVariable('x8', lowBound=0, cat='Integer')
x9 = LpVariable('x9', lowBound=0, cat='Integer')
x10 = LpVariable('x10', lowBound=0, cat='Integer')

# define the problem
Problem = LpProblem('transshipment problem',LpMinimize)

# objective function
Problem += 7*x1 + 4*x2 + 6*x3 + 7*x4 + 3*x5 + 9*x6 + 5*x7 + 9*x8 + 7*x9 + 2*x10 

# define constraints
Problem += x1 + x2 <= 200
Problem += x3 + x7 == 30
Problem += x4 + x8 == 20
Problem += x5 + x9 == 40
Problem += x6 + x10 == 50
Problem += x1 == x3 + x4 + x5 + x6
Problem += x2 == x7 + x8 + x9 + x10

# solving the problem
Problem.solve()

# show the result
print('Status:', LpStatus[Problem.status])
print('Objective function value = ', value(Problem.objective))

for i in Problem.variables():
    print(i.name, '=', i.varValue)

P/s: If you find the post useful, share it to remember and to help other people as well.

Leave a Reply

Your email address will not be published. Required fields are marked *