2016-06-24 31 views
0

我原本是使用递归来创建我的树,只有我有评分的树叶,但是因为我需要知道深度才能知道是最小还是最大,我切换到depth=0开始。然而,由于有时候currentRoot.ia = None因为没有得分已经被计算得那么深。我想要的是跟踪深度,并找到currentRoot.ia评估过的最深的叶子,以及每个叶子深度的最小值。Python递归树或fowards?修复和简化代码

我检查是否有孙辈,因为当我评估一个得分的位置时,我还添加了一个给出该得分的移动节点,所以在叶节点处不应该有任何分数。得分来自发动机的角度,所以我必须在奇怪的深处否定,尽管如果我总是最大化得分,也许我可以逃避。

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 
+0

那么......问题是什么? –

+0

@Tadhg currentRoot.score = measure(c在currentRoot.children中的c.score) TypeError:无法订购的类型:NoneType Josh

+0

下一次请在问题中发布错误,如果可能的话整个回溯。 –

回答

0

我在想这可能会解决我的错误,但我不觉得它是优雅的。我递归直到我发现一个值,所以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 
+0

其实这有一个问题currentRoot.score = measure(c在currentRoot.children中的c.score) TypeError:无法订购的类型:NoneType Josh