Question

I decision trees implemented in Python as dictionaries. Example:

sampletree = {'spl':'foo', 'go_r':{'cut':150} ,  'l':{'val':100}, 'r':{'val':200}}

I have a recursive function prints the tree:

def TREE_PRINT(tree, indent=''):
    #is this a leaf node?
    if 'val' in tree:
        print str(tree['val'])
    else:
        #print the criteria
        print 'split: '+ str(tree['spl']) + ' ' + str(tree['go_r'])
        #print the branches
        print indent+'L->', TREE_PRINT(tree['l'], indent+'  ')
        print indent+'R->', TREE_PRINT(tree['r'], indent+'  ')

How do I suppress the None's that are printed when I run the function?

TREE_PRINT(sampletree)
split: foo {'cut': 150}
L-> 100
None
R-> 200
None

I tried returning '', but then I get line unwanted extra line breaks. I'm building off of the 'printtree' function from page 151 in Programming Collective Intelligence.

Was it helpful?

Solution

The return value of your function is None. Don't print the return value of your function - just call your function.

def TREE_PRINT(tree, indent=''):
    #is this a leaf node?
    if 'val' in tree:
        print str(tree['val'])
    else:
        #print the criteria
        print 'split: '+ str(tree['spl']) + ' ' + str(tree['go_r'])
        #print the branches
        print indent+'L->',
        TREE_PRINT(tree['l'], indent+'  ')

        print indent+'R->',
        TREE_PRINT(tree['r'], indent+'  ')

Result

split: foo {'cut': 150}
L-> 100
R-> 200

See it working online: ideone

OTHER TIPS

You need to decide if TREE_PRINT prints the string representation or returns it. If you mean that it should print the data, then what you want your code to be is:

def TREE_PRINT(tree, indent=''):
    #is this a leaf node?
    if 'val' in tree:
        print str(tree['val'])
    else:
        #print the criteria
        print 'split: '+ str(tree['spl']) + ' ' + str(tree['go_r'])
        #print the branches
        print indent+'L->',
        TREE_PRINT(tree['l'], indent+'  ')
        print indent+'R->',
        TREE_PRINT(tree['r'], indent+'  ')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top