Minimax python - how to efficiently find alternating max and mins in a tree

99封情书 提交于 2019-12-12 00:45:40

问题


The following code I'm using to minimax a tree looks awful. Surely there is a way to simplify this and use a function instead of a int.MaxValue

if depth%2==1:
    min = 9999
    for child in currentRoot.children:
        if child.score < min:
            min = child.score
    currentRoot.score = min
else:
    max = -9999
    for child in currentRoot.children:
        if child.score > max:
            max = child.score
    currentRoot.score = max
return currentRoot.score

回答1:


First, don't use min and max for variable names as this shadows the built-in functions. Second, use these built-in functions!

You can use your current logic to pick out whether you want min or max and then pass a generator expression to access each child's score.

measure = min if depth % 2 else max
return measure(c.score for c in currentRoot.children)



回答2:


def findNewScore(isEven):
    if isEven:
        root.score = max([c.score for c in root.children] + [-999])
    else:
        root.score = min([c.score for c in root.children] + [999])
    return root.score

Or even just:

def findNewScore(isEven):
    s = sorted(c.score for score in root.children)
    if isEven:
        root.score = max([-999, s[-1]])
    else:
        root.score = min([999, s[0]])
    return root.score


来源:https://stackoverflow.com/questions/37973944/minimax-python-how-to-efficiently-find-alternating-max-and-mins-in-a-tree

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!