循环中的Python约束



我正在使用python-constraint库,出现了一个逻辑错误。

在我看来,这里也提出了类似的问题,但我不明白如何将其应用于

首先我把这个代码称为

my_function(List):
from constraint import Problem , AllDifferentConstraint
problem = Problem()
people = ["bob", "tom"]
times = ["2:00", "3:00"]
t_vars = list(map(lambda x: "t_"+x, people))
problem.addVariables(t_vars, times)
problem.addConstraint(AllDifferentConstraint(), t_vars)
for person in List:
problem.addConstraint (
(lambda x:  
(x == person[1])
),
["t_"+person[0]]
)
return problem.getSolutions()

然后我用打电话

my_function([["bob", "2:00"], ["tom", "3:00"]])

并且返回空的CCD_ 2。为什么?

但是,如果我进入

my_function([["bob", "2:00"]])

它返回我想要的,即[{'t_bob': '2:00', 't_tom': '3:00'}]

根据另一篇文章的答案,我提出了这个解决方案,它很有效:

def generate_constrained_func(val_in_dict):
def constraint_func(x):
return (x == val_in_dict)
return constraint_func
for person in List:
if(person):
problem.addConstraint(generate_constrained_func(person[1]), (["t_"+person[0]]))

最新更新