【问题标题】:NameError at / free variable 'y' referenced before assignment in enclosing scopeNameError at / free variable 'y' 在封闭范围内赋值之前引用
【发布时间】: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


    【解决方案1】:

    在供应限制中,将Distributors 分配给y(目前y 未定义),如下所示:

    for x in Warehouses:
        prob += lpSum([route_vars[x][y] for y in Distributors]) <= supply[x], "Sum of Products out of Warehouse %s"%x
    

    同样的错误适用于应将Warehouses 分配给x 的需求约束。

    对于部署 Apache 和 mod_wsgi 是一种选择。 https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/modwsgi/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多