【发布时间】:2020-04-29 09:59:56
【问题描述】:
我需要为我的大学创建一个小项目 - 创建可以解决交通问题的 webapp,我正在制作 MVP 版本。我将 Django 用于 webapp,将 PuLP 用于运输问题部分。
在启动我的问题解决逻辑时,我收到一个错误:
NameError at / free variable 'y' 在赋值之前引用 封闭范围
换行:
prob += lpSum([route_vars[x][y] for x in Distributors]) <= supply[x], "Sum of Products out of Warehouse %s"%x
我正在使用他们的 GitHub here 中的 PuLP 示例
我这部分的代码如下:
Warehouses = [0,1,2]
supply = { 0: deliver1,
1: deliver2,
2: deliver3
}
Distributors = [0, 1, 2]
demand = { 0: receiver1,
1: receiver2,
2: receiver3
}
costs = [ #dsitributors -static variables for debugging will change that later on
#D E F
[3, 5, 7],#A Warehouse
[12, 10, 9],#B Warehouse
[13, 3, 9],#C Warehouse
]
prob = LpProblem("Transportation Problem",LpMinimize)
Routes = [(x,y) for x in Warehouses for y in Distributors]
route_vars = LpVariable.dicts("Route",(Warehouses,Distributors),0,None,LpInteger)
prob += lpSum([route_vars[x][y]*costs[x][y] for (x,y) in Routes]), "Sum of Transporting Costs"
for x in Warehouses:
prob += lpSum([route_vars[x][y] for x in Distributors]) <= supply[x], "Sum of Products out of Warehouse %s"%x
for y in Distributors:
prob += lpSum([route_vars[x][y] for y in Warehouses]) >= demand[y], "Sum of Products into Distributors %s"%y
prob.writeLP("TransportationProblem.lp")
prob.solve()
print("Status:", LpStatus[prob.status])
for v in prob.variables():
print(v.name, "=", v.varValue)
print("Total Cost of transportation = ", value(prob.objective))
我想这只是我犯的一些愚蠢的错误,但我无法真正找到它......另外,用数字而不是名称命名仓库和分销商是我接收的解决方法
TypeError: 列表索引必须是整数或切片,而不是 str
对于同一行。
【问题讨论】:
标签: python django mathematical-optimization pulp