1

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
2
  • 1
    Is there any reason for using global x in this code? You're not accessing it in the code, and you're already returning it, so what is the purpose of making x global? (And the reason why it complains is because if it jumps straight to x the variable x would be undefined.) Commented Dec 3, 2014 at 6:08
  • Rufflewind's comment is the answer (plus a bit of good advise) Commented Dec 3, 2014 at 6:13

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

this works to an extent but I am having issues because when it jumps to the return statement it's obviously none and that is causing a problem
You probably have a problem with your data in your tree. It's quite impossible to tell without knowing the structure and actual data. Trees don't really have "rows" for one thing..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.