Reputation: 303
I have the following function and from time to time it returns the error "global name 'x' is not defined" which occurs when it jumps to the return statement. I would like help improving this code without losing functionality. Any insight would be greatly appreciated.
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
Upvotes: 1
Views: 78
Reputation: 2288
This may help...
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
Upvotes: 2