gpt4 book ai didi

python - 在递归代码中用 return 替换 Yield

转载 作者:行者123 更新时间:2023-12-01 08:37:01 26 4
gpt4 key购买 nike

如何删除此代码中的yield语句,并将其用作带有return语句的普通函数?

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

该解算器适用于三角纸牌游戏,有 15 个索引。game_board 结构是一个元组,包含棋盘上占用的空间数量和一个包含 15 个元素的数组,其中包含 1 或 0,具体取决于那里是否有钉子。

我已尽力将 (move,solved_num_ocpied),solved_game_board 存储在一个数组中,并在其中一个 for 循环后返回它们,但它总是出现空的。我想我只是不太明白生成器是如何运行的,以及它在哪里终止。任何帮助将不胜感激!

如果需要的话,这里是完整的代码(注意:我在将其放在这里之前更改了函数中的变量名称,以使其更容易理解):https://pastebin.com/raw/dEyLY2SH

最佳答案

一次积累所有内容并返回,而不是一次产生一个。正如我在评论中所说,只需将每个 yield 调用替换为对 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

关于python - 在递归代码中用 return 替换 Yield,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53662848/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com