Skip to content

Instantly share code, notes, and snippets.

@ricardosiri68
Last active January 2, 2016 18:39
Show Gist options
  • Save ricardosiri68/8344767 to your computer and use it in GitHub Desktop.
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…
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