字典值+ =纸浆

时间:2019-10-29 18:40:26

标签: python dictionary pulp

在Pulp中设置约束时,我希望能够为字典值提供一个for循环:y [i] + x [i] = y [i + 1]

我尝试使用i + 1,但是它不起作用,因为变量是字典的一部分。尽管#Constraints代码可以在下面工作,但是通过对字典键进行硬编码,我的实际项目需要更多行。

这是我尝试过的:

#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

1 个答案:

答案 0 :(得分:0)