Python生成器在递归实现minimax时遇到麻烦

时间:2018-02-26 13:17:57

标签: python recursion generator minimax

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

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函数中,line - cells = state.getAvailableCells()给出''generator'对象没有属性'getAvailableCells'“ 有谁能帮我解决这个问题? (我是物理学的学生,对Python的知识有限。我去了各种现有的问题,但是听不懂。)

1 个答案:

答案 0 :(得分:0)

这里

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]