2011-12-05 59 views
1

我在Python中以字典形式實現的決策樹。例如:用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」函數。

回答

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

+0

謝謝!逗號讓我困惑 - 我以前從來沒有使用過這種語法。我會盡快讓我接受。 – Dan

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