Python递归树还是fowards?修正和简化cod

2024-05-20 17:10:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我最初是使用递归从只有我评估分数的叶子最小化我的树,但是因为我需要知道深度来知道是最小还是最大,我切换到从depth=0开始。然而,由于没有计算出那么深的分数,所以有时会出现错误。我想要的是跟踪深度,找到已经被currentRoot.ia评估过的最深的叶子,以及每个叶子深度的极小值。你知道吗

我检查是否有孙子,因为当我评估一个位置以获得分数时,我还添加了一个给出该分数的移动节点,所以叶节点上不应该有任何分数。分数是从引擎的角度来看的,所以我不得不在奇怪的深度否定,尽管如果我总是把分数最大化,也许我可以不这样做。你知道吗

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

Tags: inchildforlenreturnif节点else
1条回答
网友
1楼 · 发布于 2024-05-20 17:10:20

我想这也许能解决我的错误,但我觉得这并不优雅。我递归,直到我找到一个值,所以ia不是无,我更深入,直到我发现我在一个树没有被进一步评估的叶子。你知道吗

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

相关问题 更多 >