首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python递归树还是向前?修复和简化代码

Python递归树还是向前?修复和简化代码
EN

Stack Overflow用户
提问于 2016-06-25 02:05:42
回答 1查看 98关注 0票数 0

我最初是使用递归来最小化树叶中的最大值,只有我可以计算分数,但因为我需要知道最小或最大值的深度,所以我切换到从depth=0开始。然而,错误,因为有时currentRoot.ia = None,因为没有分数已经计算了那么深。我想要的是跟踪深度,并找到currentRoot.ia计算过的最深的叶子,以及每个叶子的最小最大深度。

我检查是否有孙子节点,因为当我评估一个位置以获得分数时,我还添加了一个给出该分数的移动节点,因此在叶节点上不应该有任何分数。分数是从引擎的角度来看的,所以我不得不在奇怪的深度进行否定,尽管如果我总是最大限度地提高分数,也许我可以逃脱惩罚。

代码语言:javascript
运行
复制
def minimax(currentRoot, depth):
    if len(currentRoot.children) > 0 and len(currentRoot.children[0].children) > 0: #There are grandchildren
        for child in currentRoot.children:
            minimax(child, depth+1)
    else:           
        if depth%2 == 0:
            currentRoot.score = currentRoot.ia
        else:
            currentRoot.score = -currentRoot.ia
        return currentRoot.score

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

回答 1

Stack Overflow用户

发布于 2016-06-25 07:41:49

我认为这可能会解决我的错误,但我不认为它是优雅的。我递归,直到我找到一个值,所以ia不是None,我继续深入,直到我发现我在一棵树没有被进一步评估的叶子上。

代码语言:javascript
运行
复制
def minimax(currentRoot, depth):
    notAtLeaf = True
    if currentRoot.ia is None:
        notAtLeaf = False
        for child in currentRoot.children:
            minimax(child, depth+1)
    else: #currentRoot.ia is not None
        for child in currentRoot.children:
            if child.ia is not None:
                notAtLeaf = False
                minimax(child, depth+1)

    if notAtLeaf:
        if depth%2 == 0:
            currentRoot.score = currentRoot.ia
        else:
            currentRoot.score = -currentRoot.ia
        return currentRoot.score

    measure = min if depth % 2 else max
    currentRoot.score = measure(c.score for c in currentRoot.children)
    return currentRoot.score
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38019582

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档