Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 为什么';这个布尔变量在或工具中不起作用吗?_Python_Or Tools_Constraint Programming - Fatal编程技术网

Python 为什么';这个布尔变量在或工具中不起作用吗?

Python 为什么';这个布尔变量在或工具中不起作用吗?,python,or-tools,constraint-programming,Python,Or Tools,Constraint Programming,我回到谷歌的或工具,尝试一个(相对)简单的优化。我正在使用CP SAT解算器,我可能缺少一些基本的东西。 我有一些变量x,y和一些常数c。如果y小于c,我希望x等于1,否则为0 from ortools.sat.python import cp_model solver = cp_model.CpSolver() model = cp_model.CpModel() c = 50 x = model.NewBoolVar(name='x') y = model.NewIntVar(name='

我回到谷歌的或工具,尝试一个(相对)简单的优化。我正在使用CP SAT解算器,我可能缺少一些基本的东西。 我有一些变量x,y和一些常数c。如果y小于c,我希望x等于1,否则为0

from ortools.sat.python import cp_model

solver = cp_model.CpSolver()
model = cp_model.CpModel()
c = 50
x = model.NewBoolVar(name='x')
y = model.NewIntVar(name='y', lb=0, ub=2**10)

model.Add(x == (y < c))

model.Maximize(x+y)

status = solver.Solve(model)

看来我在这里滥用了约束的工具或语法。我很难理解联机的文档或工具,而且我似乎忘记了比我想象的更多的东西。

根据来自的一个示例,您几乎做到了

构建
x==(y
约束 案例1:
x=true
如果
x
true
,则
y
也必须为
true
。这正是
OnlyEnforceIf
方法的用途。如果
OnlyEnforceIf
的参数为
true
,则
Add
方法中的约束将被激活:

model.Add(y < c).OnlyEnforceIf(x) 
由于对于
x=false
x.Not()
将为
true
,因此将激活约束
y>=c
,并在求解方程时使用

完整代码
来自ortools.sat.python导入cp_模型
solver=cp_model.CpSolver()
model=cp_model.CpModel()
c=50
x=model.NewBoolVar(name='x')
y=model.NewIntVar(name='y',lb=0,ub=2**10)
模型。添加(y=c).OnlyEnforceIf(x.Not())
最大化模型(x+y)
状态=求解器。求解(模型)
model.Add(y < c).OnlyEnforceIf(x) 
model.Add(y >= c).OnlyEnforceIf(x.Not())
from ortools.sat.python import cp_model

solver = cp_model.CpSolver()
model = cp_model.CpModel()
c = 50
x = model.NewBoolVar(name='x')
y = model.NewIntVar(name='y', lb=0, ub=2**10)

model.Add(y < c).OnlyEnforceIf(x) 
model.Add(y >= c).OnlyEnforceIf(x.Not())

model.Maximize(x+y)

status = solver.Solve(model)