在Pulp中设置约束时,我希望能够为字典值设置for循环:y[I]+x[I]=y[I+1]
我试过使用I+1,但它不起作用,因为变量是字典的一部分。虽然下面的#约束代码可以工作,但是通过硬编码字典键,我的实际项目需要更多的行。你知道吗
这就是我尝试过的:
#Constraints
prob+= y_vars[1] == 50
prob+= (0.95*y_vars[i]) + (x_vars[i]) == (y_vars[i+1])
这是有效的代码:
#Create Dictionaries
repair= {1:6000,
2:7000,
3:8000,
4:9500,
5:11000}
time = [1,2,3,4,5]
#Problem
prob = LpProblem("WorkSchedule",pulp.LpMinimize)
#Set Variables
x_vars = pulp.LpVariable.dicts("Train",time,0)
y_vars = pulp.LpVariable.dicts("Technicians",time,0)
#Objective function
prob += lpSum(1000*x_vars[i] for i in time) + lpSum(2000*y_vars[i] for i in time)
#Constraints
prob+= y_vars[1] == 50
prob+= (0.95*y_vars[1]) + (x_vars[1]) == (y_vars[2])
prob+= (0.95*y_vars[2]) + (x_vars[2]) == (y_vars[3])
prob+= (0.95*y_vars[3]) + (x_vars[3]) == (y_vars[4])
prob+= (0.95*y_vars[4]) + (x_vars[4]) == (y_vars[5])
#Solve
prob.solve()
for v in prob.variables():
print(v.name, "=", v.varValue)
print("Min cost = ", value(prob.objective))
正确结果:
Technicians_1 = 50.0
Technicians_2 = 47.5
Technicians_3 = 53.578168
Technicians_4 = 62.349398
Technicians_5 = 68.75
Train_1 = 0.0
Train_2 = 8.4531681
Train_3 = 11.450138
Train_4 = 9.5180723
Train_5 = 0.0
Min cost = 593776.5104
使用
LpVariable.matrix()
参见https://github.com/coin-or/pulp/blob/bac6d9d2214ba773d638d2de5149940cfd711359/examples/test5.py以获取示例
相关问题 更多 >
编程相关推荐