Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Using Python-Constraint to solve the eight queens puzzle
#!/usr/bin/env python2
from constraint import *
problem = Problem()
cols = range(1,9) # these are the variables
rows = range(1,9) # these are the domains
problem.addVariables(cols, rows) # adding multiple variables at once
# that each queen has to be in a separate column is
# implied through the loop and added constraints
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 # this is the diagonal check
row1 != row2, (col1, col2)) # this is the horizontal check
solution = problem.getSolution()
print solution
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.