Reputation: 3838
How would I remove the yield statements in this code, and instead use it as a normal function with return statements?
def solve(game_board):
num_occupied, board_layout=game_board
if num_occupied < 2:
yield (None, game_board)
else:
for move in possible_moves():
new_game_board = do_move(game_board, move)
if new_game_board:
for item in solve(new_game_board):
solved_num_occupied, solved_game_board = item
yield (move, solved_num_occupied), solved_game_board
The solver is for a triangular game of peg solitaire, with 15 indices.
The game_board
structure is a tuple, containing the number of occupied spaces on the board and an array with 15 elements, containing 1 or 0 depending on whether there is a peg there.
I have tried my best by storing the (move, solved_num_occupied), solved_game_board
in an array and returning them after one of the for
loops, but it always comes out empty. I think I just don't really understand how the generator operates, and where it terminates. Any help would be much appreciated!
Here is the full code, if needed (note: I changed the variable names in the function before putting it here to make it more understandable): https://pastebin.com/raw/dEyLY2SH
Upvotes: 2
Views: 771
Reputation: 402363
Accumulate everything at once and return, instead of yielding one at a time. Like I said in my comment, just replace every yield
call with a call to list.append
.
def solve(game_board):
# Initialise your list.
moves = []
num_occupied, board_layout=game_board
if num_occupied < 2:
# First change.
moves.append((None, game_board))
else:
for move in possible_moves():
new_game_board = do_move(game_board, move)
if new_game_board:
for item in solve(new_game_board):
solved_num_occupied, solved_game_board = item
# Second change
moves.append(((move, solved_num_occupied), solved_game_board))
# Final change.
return moves
Upvotes: 1