2011-12-05 5 views
1

ディシジョンツリーはPythonで辞書として実装されています。例:Pythonでディシジョンツリーを印刷するための再帰関数:Suppress 'なし'

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 

私は ''を返そうとしましたが、不要な余分な改行が発生しました。 私はProgramming Collective Intelligenceの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+' ')