简体   繁体   English

使用Python约束解析器求解N个皇后

[英]Solving N-Queens Using Python constraint Resolver

Below is a solution for the N-queens problem using the Python-Constraint Resolver from Labix . 以下是使用LabixPython-Constraint Resolver解决N-皇后问题的方法。 Could someone explain to me, or refer me to any web page where it explains the meaning of the last 3 lines of this code? 有人可以向我解释一下,还是可以将我引到任何可以解释此代码后三行含义的网页?

Moreover, how could I use the AllDifferentConstraint constraint to make the below code shorter? 此外,如何使用AllDifferentConstraint约束来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))

This is roughly equivalent to this: 这大致等于:

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))

And that last line is equivalent to this: 最后一行与此等效:

func = constraintFunction(col1, col2)
problem.addConstraint(func, (col1, col2))

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

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