1

我在 Python 中将决策树实现为字典。例子:

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

我有一个递归函数打印树:

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+'  ')

如何抑制运行该函数时打印的 None ?

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

我尝试返回'',但随后我得到了不需要的额外换行符。我正在从 Programming Collective Intelligence 的第 151 页开始构建“printtree”功能。

4

2 回答 2

3

您的函数的返回值为无。不要打印函数的返回值 - 只需调用您的函数。

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+'  ')

结果

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

在线查看它:ideone

于 2011-12-05T21:28:56.093 回答
1

您需要决定是TREE_PRINT打印字符串表示还是返回它。如果您的意思是它应该打印数据,那么您想要的代码是:

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+'  ')
于 2011-12-05T21:31:03.837 回答