【问题标题】:Trouble with Python generators in recursive implementation of minimax在 minimax 的递归实现中 Python 生成器的问题
【发布时间】:2018-08-05 23:13:27
【问题描述】:

我正在研究解决 2048 的 minimax 算法的实现。在迭代对象列表并将此值传递给递归函数时遇到问题。代码是:

def MAXIMIZE(state,deep):
if deep == 10:
    return (None,greed(state))

tup = (None, -1000000) #maxChild, maxUtility 
moves = state.getAvailableMoves()
#children by moves
children = []
children.append(state.clone().move(m) for m in moves)
for child in children:
    temp,utility = MINIMIZE(child,deep + 1)
    if utility > tup[1]:
        tup = (child, utility)

return tup
def MINIMIZE(state,deep):
if deep == 10:
    return (None, greed(state))
tup = (None, +10000000)

cells = state.getAvailableCells() # this is where I get an error - "'generator' object has no attribute 'getAvailableCells'"

children = []
children.append(state.clone().setCellValue(cell, 2) for cell in cells)
for child in children:
    temp,utility = MAXIMIZE(child,deep + 1)
    if utility < tup[1]:
        tup = (child,utility)
return tup

在 MINIMIZE 函数中,行 - cells = state.getAvailableCells() 给出“'generator' object has no attribute 'getAvailableCells'” 谁能帮我解决这个问题? (我是物理系的学生,对Python的了解有限。我去各种现有的问题,但不能理解。)

【问题讨论】:

  • 修复缩进。这不运行。

标签: python recursion generator minimax


【解决方案1】:

这里

children = []
children.append(state.clone().move(m) for m in moves)

您创建一个空的list,然后向其中添加一个元素,这个元素是一个生成器(由state.clone().move(m) for m in moves generator expression 创建)。

您想要的是一个列表表达式 - 将这两行替换为:

children = [state.clone().move(m) for m in moves)]

这将评估生成器并从中构建和填充列表。

请注意,您在这里遇到了同样的问题:

children = []
children.append(state.clone().setCellValue(cell, 2) for cell in cells)

需要同样的修复:

children = [state.clone().setCellValue(cell, 2) for cell in cells]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-03
    • 2022-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-22
    • 2016-05-03
    • 1970-01-01
    相关资源
    最近更新 更多