Last active
January 2, 2016 18:39
-
-
Save ricardosiri68/8344767 to your computer and use it in GitHub Desktop.
# Problema de las 8 Reinas Es un problema bastante conocido, se trata de ubicar 8 reinas en un tablero sin que se amenacen entre si.
En la pag 226 del libro Beginning Python de Magnus Lie Hetland: Inicia una demostración del uso que tienen los generadores en problemas que requieren el uso de técnicas de recursividad como lo este problema.
Interv…
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
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) | |
def allSolutions(): | |
for solution in queens(): | |
prettyprint(solution) | |
print "" | |
if __name__ == "__main__": | |
allSolutions() | |
print "Existen %s SOLUCIONES POSIBLES" % len(list(queens())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment