如何使用 Pulp python 优化字典中的变量组合?

how to optimize variables combination in a dictionary using Pulp python?

如果这是一个糟糕的问题,请原谅我。但是如何优化字典中的一组变量呢?

我张贴了我的问题的 excel 图片。最大成本是 169 而我必须 select 4/6 五成本才能获得最大利润?所以我的目标是结合 4/6(最大利润)和 169 美元的成本限制。

我能够学会从基本方程中得到最大值,但无法扩展以帮助解决我的示例。

 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)    

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

这是 "knapsack" 问题的一个示例 - 您想要挑选最有价值的物品,但要受到可以选择的 number/cost 的限制。

以下:

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)