Created
August 21, 2012 13:19
-
-
Save cztchoice/3415317 to your computer and use it in GitHub Desktop.
eight queens solution from Beginning Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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