2014-12-03 84 views
1

我有以下函數,並且它不時地返回錯誤「全局名稱x未定義」,它在跳轉到return語句時發生。我希望幫助改進此代碼而不會丟失功能。任何有識之士將不勝感激。Python:幫助提高遞歸函數

def label(tree, instance, class_labels): 
    '''Returns the label at the end of every "branch" in the tree''' 
    global x 
    for row in tree: 
     if row[0] == instance[row[1]]: 
      if row[2][0] in class_labels: 
       x = row[2][0] 
       return x 
      else: 
       x = label(row[2], instance, class_labels) 
    return x 
+1

是否有*任何理由*對該代碼使用'全球x'?你沒有在代碼中訪問它,並且你已經在返回它,那麼使'x'成爲全局的目的是什麼? (而它之所以抱怨是因爲如果它直接跳轉到'x'變量'x'將是不確定的。) – Rufflewind 2014-12-03 06:08:20

+0

Rufflewind的評論是答案(加上一點點好的建議) – 2014-12-03 06:13:11

回答

2

這可以幫助...

def label(tree, instance, class_labels): 
    '''Returns the label at the end of every "branch" in the tree''' 
    last = None 
    for row in tree: 
     if row[0] == instance[row[1]]: 
      if row[2][0] in class_labels: 
       return row[2][0] 
      next = label(row[2], instance, class_labels) 
      if next is not None: 
       last = next 
    return last 
+0

這在一定程度上有效,但我是有問題,因爲當它跳轉到返回語句時,顯然沒有,並且導致問題 – user3318660 2014-12-03 06:47:29

+0

您的樹中的數據可能有問題。不知道結構和實際數據是完全不可能的。樹木沒有一個真正的「行」。 – 2014-12-03 07:02:51