Python 生成器在 minimax 的递归实现中出现问题
Trouble with Python generators in recursive implementation of 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 函数中,行 - cells = state.getAvailableCells() 给出“'generator' object has no attribute 'getAvailableCells'”
谁能帮我解决这个问题? (我是学物理的,对Python的了解有限,翻了各种现成的题,也没看懂。)
这里
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]
我正在研究 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 函数中,行 - cells = state.getAvailableCells() 给出“'generator' object has no attribute 'getAvailableCells'” 谁能帮我解决这个问题? (我是学物理的,对Python的了解有限,翻了各种现成的题,也没看懂。)
这里
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]