2
我的代碼工作,如果喜歡這樣做使用addConstraint變量產生錯誤的答案,但沒有使用變量工作正常
from constraint import *
import itertools
def main():
problem = Problem()
x = [0,1,2,3]
f = list(itertools.product(x,x,x,x))
problem.addVariable("a", f)
problem.addConstraint(lambda a: a[0] == a.count(0), "a",)
problem.addConstraint(lambda a: a[1] == a.count(1), "a",)
problem.addConstraint(lambda a: a[2] == a.count(2), "a",)
problem.addConstraint(lambda a: a[3] == a.count(3), "a",)
solutions = problem.getSolutions()
print "Found %d solutions!" % len(solutions)
答案是[{'a': (2, 0, 2, 0)}, {'a': (1, 2, 1, 0)}]
但如果我使用變量它進入瘋狂
from constraint import *
import itertools
def main():
problem = Problem()
x = [0,1,2,3]
f = list(itertools.product(x,x,x,x))
problem.addVariable("a", f)
x = 0
problem.addConstraint(lambda a: a[x] == a.count(0), "a",)
x = 1
problem.addConstraint(lambda a: a[x] == a.count(1), "a",)
x = 2
problem.addConstraint(lambda a: a[x] == a.count(2), "a",)
problem.addConstraint(lambda a: a[3] == a.count(3), "a",)
solutions = problem.getSolutions()
print "Found %d solutions!" % len(solutions)
其結果爲空列表。我想能夠把它放在一個循環中,但我不知道發生了什麼。我可能只是錯過了一些非常基本的東西,但它只適用於我使用實際數字