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

如何使用python优化字典中的变量组合?,python,optimization,scipy,linear-programming,pulp,Python,Optimization,Scipy,Linear Programming,Pulp,如果这是一个糟糕的问题,请原谅我。但是如何优化字典中的一组变量呢 我贴了一张我的问题的excel图片。其中最大成本为169,我必须选择4/6五成本才能获得最大利润?因此,我的目标是实现4/6的最大利润和169美元的成本限制 我能够从一个基本方程中得到最大值,但无法扩展以帮助解决我的示例 x1 = pulp.LpVariable("x1", 0, 40) # 0<= x1 <= 40 x2 = pulp.LpVariable("x2", 0, 1000) # 0<= x2

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

我贴了一张我的问题的excel图片。其中最大成本为169,我必须选择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)    

资料来源:

这是背包问题的一个例子——你想挑选最有价值的物品,但对所选物品的数量/成本有限制

以下是:

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)

我不明白这意味着什么:选择4/5五个成本我只能从5个位置中选择4个位置。对不起,应该更清楚。哪5个?我看到了6种可能性。非常抱歉。你是对的,它是6。这是一个微不足道的优化模型。只需使用二进制变量x[i]指示是否选择了项目i。
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)