Skip to main content

How the Davengers Solved a Linear Programming Problem using Python

 Maximizing Profit through Linear Optimization

Recap: In the previous blog, we introduced you to the latest challenge for Davengers, who were hired by Lightworks Company to optimize the production of two products — Product A and Product B.
Here is the problem statement for those who didn’t read the first part.
The Challenge Summary
Lightworks Company produces two products, Product A and Product B.
  • Product A requires 1 unit of frame parts and 2 units of electrical components.
  • Product B requires 3 units of frame parts and 2 units of electrical components.
  • Lightworks has 200 units of frame parts and 300 units of electrical components.
  • Each unit of Product A gives a profit of $2.
  • Each unit of Product B gives a profit of $4, but only up to 50 units. Any more than 50 units yields no additional profit.

The LP Formulation Recap
The team formulated the Linear Programming (LP) model as given below:
Objective function: Maximize profit
Z=2x+4y, where:
  • x = units of Product A produced,
  • y = units of Product B produced.
Press enter or click to view image in full size
Now, it’s time to solve the problem.
Enter the Davengers: Tackling Linear Programming with Python
The Davengers are gathered at Arjun’s place, armed with laptops and coffee, ready to tackle Lightworks’ problem.
Aarav, never in the mood of work, says, “Alright, team. This should be easy for us. We just need to find the right numbers to maximize the client’s profits. Simple!”
Sakshi, smiles and replies, “Easy for you, Aarav. You just sit back while the rest of us do the work. Let’s break out the Python and actually solve the problem.”
Ananya pulls out her laptop. “Okay, let’s do this. ” Here’s how Ananya sets up the Linear Programming problem using Python’s `SciPy` library.
from scipy.optimize import linprog

# Coefficients of the objective function (this has been negated because linprog minimizes by default)
c = [-2, -4] # We are maximizing profit, so we negate the coefficients.

# Coefficients of the inequality constraints
A = [[1, 3], # Coefficients for frame parts constraint
[2, 2]] # Coefficients for electrical components constraint

# Right-hand side of the inequality constraints
b = [200, 300] # Limits on frame parts and electrical components

# Bounds for the variables: x (Product A) and y (Product B)
x_bounds = (0, None) # Non-negativity constraint for Product A
y_bounds = (0, 50) # Limit Product B to 50 units

“We’ve set up the model in Python, the following line of code will give us the solution”, Ananya exclaimed triumphantly!

# Solving the Linear Programming problem
res = linprog(c, A_ub=A, b_ub=b, bounds=[x_bounds, y_bounds], method='simplex')

# Displaying the results
print('Optimal number of Product A to produce:', res.x[0])
print('Optimal number of Product B to produce:', res.x[1])
print('Maximum Profit:', -res.fun) # Negate again to get the maximized profit

As the Davengers looked at the code, Ananya continues explaining the code:

“This line of code — res = linprog(c, A_ub=A, b_ub=b, bounds=[x_bounds, y_bounds], method='simplex'—is where all the magic happens.

Basically, linprog is a function from the SciPy library that helps us solve Linear Programming problems.

We define the objective function coefficients (c), the constraints (A_ub and b_ub), and the bounds on the decision variables (bounds).

Then, we tell the model to use the Simplex Method to find the best solution. It calculates the optimal number of units to produce for Products A and B, all while respecting the resource constraints we’ve set.

The result gets stored in res, which includes the optimal solution and maximum profit. Easy, right?”

The Results

After running the code, Ananya smiles and reads out the results:

“This basically means that Lightworks should produce 125 units of Product A and 25 units of Product B to achieve a maximum profit of $350.”

Aarav, grinning, says, “See? I knew we had this! Lightworks owes us big time for this optimization masterclass.”

Sakshi laughs, “Aarav, you should thank Ananya, not yourself. You barely lifted a finger, and were busy staring at me.” Everyone laughs out loud!

Vikram, keeping things serious, adds, “Good work, team. $350 profit is the best outcome given the constraints on resources.”

“Three cheers to all of us!”, exclaimed Arjun, and the Davengers celebrated!

Stay tuned for more laughs, learning, and data-driven adventures in future. If you’re interested in the journey of Davengers, they have appeared in the following blogs:
  1. 10 Statistical Concepts Every Aspiring Data Scientist Should Know — The Davangers’ Guide!
  2. How to Formulate a Linear Programming Problem — the Davengers way

Collection of my other blogs could be found here.
You can also connect with me:
  • Career Counselling and Mentorship: Topmate

Comments

Popular posts from this blog

10 Projects You Can Discuss in Interviews Even If You Don't Have Work Experience

 If you are an aspiring data scientist, you might wonder what kind of projects you can talk about to stand out. The good news is that you don’t need a formal job history to have meaningful projects to discuss. Building and sharing your own projects can demonstrate your understanding of machine learning, AI, analytics, and data handling. This post lists 10 project ideas that you can create and confidently discuss in interviews. These projects cover a range of skills and tools relevant to data science and generative AI. Each project example includes practical tips on how to approach it and what you can highlight during your interview.                Data visualization dashboard created for a personal analytics project 1. Data Cleaning and Exploration Project Start with a raw dataset from sources like Kaggle or UCI Machine Learning Repository. Focus on cleaning the data by handling missing values, removing duplicates, and correcting errors....

How to Create Stunning Data Visualizations in Python: Top 10 Techniques to Learn

  A Visual Analytics Journey In this guide, you’re going to learn some of the coolest and most popular visualization techniques, one plot at a time, using the mpg dataset in Python. Whether you’re interested in visualizing univariate (histograms), bivariate (scatter plot) or multivariate (heatmaps) variables, we’ve got it all covered here in this guide. We’ll start by loading the `mpg` dataset from Seaborn, and before you know it, you’ll be the Picasso of Python plots. So lets get going! Dataset First things first, we need to grab the `mpg` dataset. Think of this dataset as a collection of cool cars from the 1970s and 80s. It’s a nostalgic look at how much fuel (miles per gallon) these cars guzzled. import seaborn as sns import pandas as pd # Load the mpg dataset from seaborn mpg = sns.load_dataset( 'mpg' ) # Display the first few rows to get a feel of the data mpg.head() Output: Boom! We’ve got a dataset full of horsepower, cylinders, and other engine-sort-of-things! L...

Phases of data science and analytics

Data Science and analytics isn’t a destination — it’s a journey of continuous learning and application. In my experience, this journey can be divided into five distinct phases:                                         5 Phases of Analytics: Image by Author 1. Descriptive Analytics: Focused on understanding what happened in the past. 2. Diagnostic Analytics: Answers the critical question: why did it happen? 3. Predictive Analytics: Often seen as the most glamorous phase, it predicts what will happen next. 4. Prescriptive Analytics: Goes a step further to recommend what should be done based on predictions; or how can you optimize business processes or decisions. 5. Automated Analytics: Finally, the ‘product/software’ development stage of analytics. It automates the process — from descriptive to predictive — making analytics accessible and actionable for business stak...