2014-12-03 87 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