### Help with N Queens

Posted:

**Thu May 16, 2013 1:16 pm**I am having a play with the N Queens problem. I have some working code, but I am not very happy with it. In the program, I make a new empty and add new (partial)solutions to it before returning the current list of (partial)solutions. I think the way I have done this looks clumsy, but I can't work out another way. Any help appreciated:

Code: Select all

```
# nqueens.py
from time import *
def main():
print("*** The N-Queens Problem ***")
n = int(input("Size of board: "))
tic = time()
answers = nQueens(n)
toc = time()
print("Time: ", toc-tic)
if not answers:
print("No solutions.")
else:
for ans in answers:
print(ans)
def nQueens(n):
"""Top-level function."""
def queens(k):
"""Recursive function."""
if k == 0:
return [[]]
else:
sols = []
for solution, row in [(s,r) for s in queens(k-1) for r in range(1, n+1)]:
if not unsafe(solution, row):
sols.append(solution + [row])
return sols
return queens(n)
def unsafe(part, r):
"""Takes a partial solution and a row. Returns True if the queen is unsafe."""
col = len(part)
for i in range(col):
if abs(part[i]-r) in (0, col-i):
return True
return False
if __name__ == "__main__":
main()
```