我正在尝试将此代码转换为函数,但将“赋值之前引用的局部变量'值'作为两个变量的错误。 我将粘贴整个代码以更好地理解
def allocator(item_mass,item_vol,truck_mass,truck_vol,truck_cost):
n_items = len(item_vol)
set_items = range(n_items)
n_trucks = len(truck_cost)
set_trucks = range(n_trucks)
y = pulp.LpVariable.dicts('truckUsed', set_trucks,
lowBound=0, upBound=1, cat=LpInteger)
x = pulp.LpVariable.dicts('itemInTruck', (set_items, set_trucks),
lowBound=0, upBound=1, cat=LpInteger)
prob = LpProblem("Truck allocatoin problem", LpMinimize)
prob += lpSum([truck_cost[i] * y[i] for i in set_trucks])
for j in set_items:
prob += lpSum([x[j][i] for i in set_trucks]) == 1
for i in set_trucks:
prob += lpSum([item_mass[j] * x[j][i] for j in set_items]) <= truck_mass[i]*y[i]
prob += lpSum([item_vol[j] * x[j][i] for j in set_items]) <= truck_vol[i]*y[i]
for j in set_items:
for i in set_trucks:
x[j][i] <= y[i]
prob.solve()
x_soln = np.array([[x[i][j].varValue for i in set_items] for j in set_trucks])
y_soln = np.array([y[i].varValue for i in set_trucks])
lpstatus = LpStatus[prob.status] #these two throw the error
value_obj = value(prob.objective) #
return lpstatus,value_obj
在原始代码中,注释行如下:
print (("Status:"), LpStatus[prob.status])
print ("Total Cost is: ", value(prob.objective))