Linear Programming in Python

in

Linear programming is essentially solving optimization problems using linear equations. Its not exactly rocket science (or maybe it is), but it can be pretty useful in real-life scenarios like resource allocation or supply chain management. And the best part? You don’t have to be a math genius to understand it! All you need is Python and some basic knowledge of linear algebra.

So, lets dive into our first example: finding the maximum profit that can be made from selling a certain number of products at different prices. Here’s how we do it in Python using the `scipy` library:

# Import necessary libraries
import numpy as np
from scipy.optimize import linprog

# Define our variables and constraints
# x represents the number of products to sell, with the first type having a price of $50 and the second type having a price of $70
x = np.array([1, 2]) 
# A represents the cost matrix for each product and resource constraint, with the first row representing the cost of each product and the second row representing the resource constraint (in this case, time and money)
A = np.array([[50, 70], [3, 4]]) 
# b represents the total available resources, with the first element representing the available budget and the second element representing the available time
b = np.array([1200, 800]) 
# c represents the objective function, which is to maximize profit. The negative sign is added to make it a minimization problem instead of a maximization problem.
c = np.array([[50*x[0] + 70*x[1], -1]]) 
# bounds represents the bounds for each variable, with the first element representing the lower bound and the second element representing the upper bound. In this case, we want x_1 and x_2 to be non-negative integers.
bounds = [(None, None), (0, 2)] 
# constraints represents the constraints for each resource. The first constraint ensures that the total cost of resources does not exceed the available budget, while the second constraint ensures that the total cost of resources does not exceed the available time.
constraints = ({'type': 'eq', 'fun': lambda x: A[0, :] @ x - b[0], 'jac': lambda x: A[0, :]}, {'type': 'ineq', 'fun': lambda x: A[1, :] @ x - b[1], 'jac': lambda x: A[1, :]}) 

# Solve the optimization problem using the linprog() function from the scipy library
result = linprog(c=c, bounds=bounds, constraints=constraints)
# Print out the maximum profit that can be made with the given resources and product prices
print("Maximum profit: $", result.fun)

You’ve just solved a linear programming problem using Python. It may not sound like much, but this is actually pretty impressive considering how complex these problems can get in real life scenarios. And the best part? This code can easily be adapted to solve other optimization problems as well all you have to do is change the variables and constraints accordingly!

Who needs math when you’ve got a computer doing all the heavy lifting for you?

SICORPS