使用 Python 约束解析器求解 N-Queens
Solving N-Queens Using Python constraint Resolver
下面是 N-queens problem using the Python-Constraint Resolver from 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))
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))
下面是 N-queens problem using the Python-Constraint Resolver from 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))
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))