极大极小树算法的实现

2024-10-06 22:50:38 发布

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

我真的不知道如何将代码实现到我给出的树上,我在做这件事时遇到了很多困难。你知道吗

作业:用python实现一个minimax算法。 在下图上运行实现并打印最终值。你知道吗

我的叶子是:{3, 12, 8} {2, 4, 6} {14, 5, 2}

import math 

def minimax (curDepth, nodeIndex, 
             maxTurn, scores,  
             targetDepth): 

    # base case : targetDepth reached 
    if (curDepth == targetDepth):  
        return scores[nodeIndex] 

    if (maxTurn): 
        return max(minimax(curDepth + 1, nodeIndex * 2,  
                    False, scores, targetDepth),  
                   minimax(curDepth + 1, nodeIndex * 2 + 1,  
                    False, scores, targetDepth)) 

    else: 
        return min(minimax(curDepth + 1, nodeIndex * 2,  
                     True, scores, targetDepth),  
                   minimax(curDepth + 1, nodeIndex * 2 + 1,  
                     True, scores, targetDepth)) 

# Driver code 
scores = [3, 5, 2, 9, 12, 5, 23, 23] 

treeDepth = math.log(len(scores), 2) 

print("The optimal value is : ", end = "") 
print(minimax(0, 0, True, scores, treeDepth)) 

Tags: 代码falsetruereturnif作业mathprint