0

Please forgive me if this is a poor question. But how do I optimize a set of variables in a dictionary?

enter image description here

I posted an excel img of my problem. Where the max cost is 169 and I have to select 4/6 five cost to get the max profit? So my goal is to have a combination of 4/6 (max profits) with a cost limit of $169.

I was able to learn to get the max from a basic equation but could not extend to help solve my example.

 x1 = pulp.LpVariable("x1", 0, 40)   # 0<= x1 <= 40
 x2 = pulp.LpVariable("x2", 0, 1000) # 0<= x2 <= 1000

 prob = pulp.LpProblem("problem", pulp.LpMaximize)

 prob += 2*x1+x2 <= 100 
 prob += x1+x2 <= 80


 prob += 3*x1+2*x2

 status = prob.solve()
 pulp.LpStatus[status]

# print the results x1 = 20, x2 = 60
  pulp.value(x1)
  pulp.value(x2)    

Source:https://thomas-cokelaer.info/blog/2012/11/solving-a-linear-programming-problem-with-python-pulp/

6
  • I don't understand what this means: "select 4/5 five cost" Commented Feb 10, 2020 at 16:50
  • I can only pick 4 locations out of the 5. Sorry, should have been clearer. Commented Feb 10, 2020 at 17:18
  • Which 5? I see 6 possibilities. Commented Feb 10, 2020 at 17:21
  • super sorry. you are right it's 6. Commented Feb 10, 2020 at 17:28
  • 1
    This is a trivial optimization model. Just use binary variables x[i] indicating if project i is selected. Commented Feb 10, 2020 at 18:22

1 Answer 1

3

This is an example of the "knapsack" problem - where you want to pick the most valuable items, subject to a limit on the number/cost that can the selected.

The following:

from pulp import *

# PROBLEM DATA:
costs = [15, 25, 35, 40, 45, 55]
profits = [1.7, 2, 2.4, 3.2, 5.6, 6.2]
max_cost = 169
max_to_pick = 4

# DECLARE PROBLEM OBJECT:
prob = LpProblem("Mixed Problem", LpMaximize)

# VARIABLES
# x_i - whether to include item i (1), or not (0)
n = len(costs)
N = range(n)
x = LpVariable.dicts('x', N, cat="Binary")

# OBJECTIVE
prob += lpSum([profits[i]*x[i] for i in N])

# CONSTRAINTS
prob += lpSum([x[i] for i in N]) <= max_to_pick        # Limit number to include
prob += lpSum([x[i]*costs[i] for i in N]) <= max_cost  # Limit max. cost

# SOLVE & PRINT RESULTS
prob.solve()
print(LpStatus[prob.status])
print('Profit = ' + str(value(prob.objective)))
print('Cost = ' + str(sum([x[i].varValue*costs[i] for i in N])))

for v in prob.variables ():
    print (v.name, "=", v.varValue)

Returns:

Optimal
Profit = 17.0
Cost = 165.0
('x_0', '=', 0.0)
('x_1', '=', 1.0)
('x_2', '=', 0.0)
('x_3', '=', 1.0)
('x_4', '=', 1.0)
('x_5', '=', 1.0)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.