【问题标题】:Minimax python - how to efficiently find alternating max and mins in a treeMinimax python - 如何有效地在树中找到交替的最大值和最小值
【发布时间】:2016-06-22 16:43:44
【问题描述】:

我用来最小化一棵树的以下代码看起来很糟糕。当然有一种方法可以简化这一点并使用函数而不是 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

【问题讨论】:

  • 我的一个想法是否定树的每一层的分数,这样我总能找到最大值,但这似乎有点棘手,因为我可以将它们全部反转并且需要根据叶子的深度找到分钟。

标签: python minimax


【解决方案1】:

首先,不要使用minmax 作为变量名,因为这会影响内置函数。其次,使用这些内置函数!

您可以使用您当前的逻辑来选择您想要min 还是max,然后传递一个生成器表达式来访问每个孩子的分数。

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

【讨论】:

  • 哦,比我的干净多了。我觉得我在反复接近类似的东西,但你打败了我。
  • 另外,如果 OP 确实需要默认的 -999999 (如果没有孩子),可能会做 default = 999 if depth % 2 else -999 然后像 measure(c.score for c in root.children, default=default) 一样使用它(我也刚学会min/max 有一个default 千瓦!)
  • @dwanderson 太酷了!但是,我不需要这些默认值。但我想知道如果我把它留空,默认是什么
  • @Jared 这忽略了分配,所以我使用这个答案: current.score = measure(c.score for c in currentRoot.children);返回 current.score
【解决方案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

甚至只是:

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

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 1970-01-01
    • 2021-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多