带有for循环的Python PuLP打印

时间:2019-01-07 13:50:40

标签: python

我得到了分配优化模型的结果。对于printint输出,我想使用“ for”循环显示从计算机到作业的所有分配。由于某种原因,它仅弹出一个任务-将机器M2分配给作业J4。您能帮助初学者了解发生了什么吗?谢谢你一百万。

from pulp import *

#List
machine = ['M1','M2','M3','M4']
job = ['j1','j2','j3','j4']

#parameter
setupcost = {'M1':{'j1':14,'j2':5,'j3':8,'j4':7},
          'M2':{'j1':2,'j2':12,'j3':6,'j4':5},
          'M3':{'j1':7,'j2':8,'j3':3,'j4':9},
          'M4':{'j1':2,'j2':4,'j3':6,'j4':10}
}

#define problem
prob = LpProblem("assignment",LpMinimize)

#define decision variable
assign_vars = LpVariable.dicts("assign machine to job", [(i,j) for i in 
machine for j in job], 0,1,LpBinary)

#obj
prob += lpSum([setupcost[i][j]*assign_vars[(i,j)] for i in machine for j in 
job])

#constraints
for i in machine:
prob += lpSum([assign_vars[(i,j)] for j in job]) == 1

for j in job:
prob += lpSum([assign_vars[(i,j)] for i in machine]) ==1

#solve
prob.solve()

#output
print("Status:",LpStatus[prob.status])


for i in machine:
if assign_vars[(i,j)].varValue >0:
    print("allocate machine", i, "to job", j)

for v in prob.variables():
print(v.name, "=", v.varValue)

print("total costs of assignment =", value(prob.objective))

这是输出:

Status: Optimal
allocate machine M2 to job j4
assign_machine_to_job_('M1',_'j1') = 0.0
assign_machine_to_job_('M1',_'j2') = 1.0
assign_machine_to_job_('M1',_'j3') = 0.0
assign_machine_to_job_('M1',_'j4') = 0.0
assign_machine_to_job_('M2',_'j1') = 0.0
assign_machine_to_job_('M2',_'j2') = 0.0
assign_machine_to_job_('M2',_'j3') = 0.0
assign_machine_to_job_('M2',_'j4') = 1.0
assign_machine_to_job_('M3',_'j1') = 0.0
assign_machine_to_job_('M3',_'j2') = 0.0
assign_machine_to_job_('M3',_'j3') = 1.0
assign_machine_to_job_('M3',_'j4') = 0.0
assign_machine_to_job_('M4',_'j1') = 1.0
assign_machine_to_job_('M4',_'j2') = 0.0
assign_machine_to_job_('M4',_'j3') = 0.0
assign_machine_to_job_('M4',_'j4') = 0.0
total costs of assignment = 15.0

[Done] exited with code=0 in 0.583 seconds

0 个答案:

没有答案