以下是使用N-queens problem Python-Constraint解析器的Labix解决方案。有人可以向我解释,或者推荐我到任何网页,它解释了这段代码的最后3行的含义吗?
此外,我如何使用AllDifferentConstraint
约束来缩短下面的代码?
from constraint import *
problem = Problem()
size = 8
cols = range(size)
rows = range(size)
problem.addVariables(cols, rows)
for col1 in cols:
for col2 in cols:
if col1 < col2:
problem.addConstraint(lambda row1, row2, col1=col1, col2=col2:
abs(row1-row2) != abs(col1-col2) and
row1 != row2, (col1, col2))
答案 0 :(得分:3)
problem.addConstraint(lambda row1, row2, col1=col1, col2=col2:
abs(row1-row2) != abs(col1-col2) and
row1 != row2, (col1, col2))
这大致相当于:
def constraintFunction (col1, col2):
def innerFunction (row1, row2):
return abs(row1 - row2) != abs(col1 - col2) and row1 != row2
return innerFunction
problem.addConstraint(constraintFunction(col1, col2), (col1, col2))
最后一行等同于:
func = constraintFunction(col1, col2)
problem.addConstraint(func, (col1, col2))