[英]Dictionary Value += In Pulp
When setting a constraint in Pulp, I'd like to be able to have a for loop for dictionary values: y[i] + x[i] = y[i+1]在 Pulp 中设置约束时,我希望能够为字典值创建一个 for 循环:y[i] + x[i] = y[i+1]
I've tried to use i+1, but it does not work because the variables are a part of a dictionary.我尝试使用 i+1,但它不起作用,因为变量是字典的一部分。 While the #Constraints code works below, by hard coding the dictionary keys, my actual project requires many more lines.虽然#Constraints 代码在下面工作,但通过对字典键进行硬编码,我的实际项目需要更多行。
This is what I've tried:这是我尝试过的:
#Constraints
prob+= y_vars[1] == 50
prob+= (0.95*y_vars[i]) + (x_vars[i]) == (y_vars[i+1])
This is the code that works:这是有效的代码:
#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))
Correct Results:正确结果:
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
Use LpVariable.matrix()
使用LpVariable.matrix()
see https://github.com/coin-or/pulp/blob/bac6d9d2214ba773d638d2de5149940cfd711359/examples/test5.py for an example有关示例,请参见https://github.com/coin-or/pulp/blob/bac6d9d2214ba773d638d2de5149940cfd711359/examples/test5.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.