python - 如何删除python中纸浆中约束的语法错误
问题描述
下面的代码在这一行的 for 循环之后显示了语法错误
model += x[int((str((i*2)-1)+str(j)))] + x[int((str(i*2)+str(j)))]] <= 1
我希望将变量声明为 2 D 数组 x11、x12、x13,因此我会出错。
KeyError
Traceback (most recent call last)
<ipython-input-95-19b3a6e81910> in <module>()
19 for i in range (1, (Box//2)+1):
20 for j in range (1,Pallet+1):
---> 21 model += x[int((str((i*2)-1)+str(j)))] + x[int((str(i*2)+str(j)))] <= 1
22
23
KeyError: 11
我检查了所有可能的选项,一切似乎都是正确的,请帮助。
'''
from pulp import *
Box=6
Pallet=3
Variable_range=Box*Pallet
from pulp import LpMaximize, LpProblem, LpStatus, lpSum, LpVariable
# Define the model
model = LpProblem(name="Container Loading", sense=LpMaximize)
# Define the decision variables
for i in range(1, Box+1):
for j in range (1,Pallet+1):
x = {int((str(i)+str(j))):LpVariable(name=f"x{i}_{j}",lowBound=0,upBound=1,cat='Integer')}
print(x)
# Add constraints
for i in range (1, (Box//2)+1):
for j in range (1,Pallet+1):
model += x[int((str((i*2)-1)+str(j)))] + x[int((str(i*2)+str(j)))]] <= 1 # error at this line
#Set the objective
model += lpSum(x.values())
# Solve the optimization problem
status = model.solve()
# Get the results
print(f"status: {model.status}, {LpStatus[model.status]}")
print(f"objective: {model.objective.value()}")
for var in x.values():
print(f"{var.name}: {var.value()}")
for name, constraint in model.constraints.items():
print(f"{name}: {constraint.value()}")
'''
解决方案
这是关于对循环的误解。在:
# Define the decision variables
for i in range(1, Box+1):
for j in range (1,Pallet+1):
x = {int((str(i)+str(j))):LpVariable(name=f"x{i}_{j}",lowBound=0,upBound=1,cat='Integer')}
print(x)
你每次都覆盖 x。所以你最终 x 只包含一个元素。您可以通过将 print 语句移到循环之后看到这一点。
更好的是:
# Define the decision variables
x = {int((str(i)+str(j))):LpVariable(name=f"x{i}_{j}",lowBound=0,upBound=1,cat='Integer')
for i in range(1, Box+1) for j in range (1,Pallet+1) }
print(x)
推荐阅读
- jquery - 鼠标移动或单击时停止时间
- java - 在我的应用程序中进行语音控制的语音识别
- javascript - 继续使用该属性到下一个请求的页面
- c# - 即使我看到来自 VSTS Web 应用程序的相关链接,C# VSTS WorkItem 相关计数字段也显示为零
- r - 特定单元格中的控制数字
- android - 在 Android Studio 中构建 APK 时会生成 Output.json。为了使应用程序正常工作,我是否需要在我的设备上复制两者?
- python - 使用 python、pytest、mock 在另一个模块中模拟第 3 方函数
- c# - Database.ExecuteSqlCommand() 挂起执行存储过程
- vba - 用于选择列定义名称的 vba 代码
- django - Django 管理员:保持安全的最佳实践