简体   繁体   English

在循环中添加约束的问题

[英]Problems with adding constraints in a loop

I have this:我有这个:

import constraint

p = constraint.Problem()

t = [0,5]
c = [3,7]

s = range(len(t))
n = 12

p.addVariables([str(i) for i in s], range(n))

p.addConstraint(lambda x: (x+t[0])%n in c, ('0'))                              
p.addConstraint(lambda x: (x+t[1])%n in c, ('1'))                              

l = [list(i.values()) for i in p.getSolutions()]

print(l)

And that outputs:那输出:

[[7, 10], [7, 2], [3, 10], [3, 2]]

But I want to add the constraints in a loop, so I did this instead of the two p.addConstraint lines:但我想在循环中添加约束,所以我这样做而不是两条p.addConstraint行:

for i in s:
    p.addConstraint(lambda x: (x+t[i])%n in c, (str(i)))

I expected this to give the same output, but instead I got this:我希望这会给出相同的 output,但我得到了这个:

[[10, 10], [10, 2], [2, 10], [2, 2]]    

What am I missing?我错过了什么?

You can use a function that creates a function and then create the functions in a for loop and add them as constrains.您可以使用 function 创建 function,然后在 for 循环中创建函数并将它们添加为约束。

import constraint

p = constraint.Problem()

t = [0,5]
c = [3,7]

s = range(len(t))
n = 12

p.addVariables([str(i) for i in s], range(n))

def generate_constrained_func(t, n, c):
    def constraint_func(x):
        return ((x+t)%n in c)
    return constraint_func

for idx, t_constraint in enumerate(t):
    p.addConstraint(generate_constrained_func(t_constraint, n, c), (str(idx)))
    
l = [list(i.values()) for i in p.getSolutions()]

print(l)

Output: Output:

[[7, 10], [7, 2], [3, 10], [3, 2]]

I did manage to solve it with eval , but I've heard that's a dangerous function so I'm trying to avoid it.我确实设法用eval解决了它,但我听说这是一个危险的 function 所以我试图避免它。 But if no one comes up with anything better, that's what I use:但是,如果没有人想出更好的方法,那就是我使用的:

for i in s:
    eval('p.addConstraint(lambda x: (x+t[%d])%%n in c, (str(i)))' % i)

It does not explain why the code in the question does not work, and I'm still curious about it.它没有解释为什么问题中的代码不起作用,我仍然对此感到好奇。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM