Skip to content

Instantly share code, notes, and snippets.

@cztchoice
Created August 21, 2012 13:19
Show Gist options
  • Save cztchoice/3415317 to your computer and use it in GitHub Desktop.
Save cztchoice/3415317 to your computer and use it in GitHub Desktop.
eight queens solution from Beginning Python
import random
def conflict(state, nextX):
nextY = len(state)
for i in range(nextY):
if abs(state[i] - nextX) in (0, nextY - i):
return True
return False
def queens(num=8, state=()):
for pos in range(num):
if not conflict(state, pos):
if len(state) == num - 1:
yield (pos, )
else:
for result in queens(num, state + (pos, )):
yield (pos, ) + result
def prettyprint(solution):
def line(pos, length=len(solution)):
return '. ' * (pos) + 'X' + ' .' * (length - pos - 1)
for pos in solution:
print line(pos)
result = list(queens())
prettyprint(random.choice(result))
#print result
print len(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment