Skip to content

Instantly share code, notes, and snippets.

@tonyromarock
Last active March 13, 2016 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tonyromarock/34168259b0fb779a2ef7 to your computer and use it in GitHub Desktop.
Save tonyromarock/34168259b0fb779a2ef7 to your computer and use it in GitHub Desktop.
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