我在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+' ')
如何抑制运行该功能时打印的无?
TREE_PRINT(sampletree)
split: foo {'cut': 150}
L-> 100
None
R-> 200
None
我试过返回'',但后来我得到了不必要的额外换行符。 我正在构建编程集体智能中的第151页的'printtree'功能。
答案 0 :(得分:3)
您的函数的返回值为None。不要打印函数的返回值 - 只需调用函数。
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+' ')
结果
split: foo {'cut': 150} L-> 100 R-> 200
查看在线工作:ideone
答案 1 :(得分: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+' ')