I want to yield the results from a recursive function (code below) but am having difficulties getting the output to match what I want. Ideally, if I call
print(list(n_queens_solutions(4)))
I would see
[[1, 3, 0, 2], [2, 0, 3, 1]]
but instead the function returns
[[], []]
I'm not too familiar with Python generators; I've tried various permutations of "yield" and "return" to no avail.
def n_queens_valid(board):
for q1 in range(len(board)):
for q2 in range (1, len(board)-q1):
if board[q1] == board[q1+q2] or board[q1+q2] == board[q1]+q2 or board[q1+q2] == board[q1]-q2:
return False
return True
def n_queens_solutions(n):
board = []
return n_queens_helper(0, board, n)
def n_queens_helper(n, board, size):
if len(board) == size:
print(board)
yield board
else:
for i in range(size):
board.append(i)
if n_queens_valid(board):
yield from n_queens_helper(n+1, board, size)
board.pop()
print(list(n_queens_solutions(4)))
The print from the last line in the code above should output: [[1, 3, 0, 2], [2, 0, 3, 1]], but instead returns [[], []].
board
. When you create the list, all theappend
andpop
are finally executed, on only oneboard
object. try passing a copy in your recursion (e.g.board[:]
)