2013-05-04 59 views
1

我試圖在Python中遞歸地打印一棵樹。出於某種原因,縮進不起作用(也許我太累了,在這一點上看到一個明顯的缺陷)。下面是我的工作結構/類定義:用分支遞歸地打印樹

class Tree(object): 
    def __init__(self, data): 
    self.data = data 
    self.branches = [] 

class Branch(object): 
    def __init__(self, value): 
    self.label = value 
    self.node = None 

正如你看到的,每棵樹都有分公司,其中有一個標籤,並點到另一個樹(這是node值可以看到有)。以下是我正在試圖打印出樹:

def __str__(self): 
    return self.tree_string(0) 

    def tree_string(self, indent): 
    indentation = indent * " " 
    result = indentation + str(self.data) + "\n"; 
    for branch in self.branches: 
     result += indentation + branch.label + ": \n" + branch.node.tree_string(indent + 2) 
    return result 

這是給我:

4 
Somewhat: 
    Yes 
Fuller: 
    3 
Correct: 
    8 
Caribbean: 
    2 
Wrong: 
    Wrong 
Correct: 
    Correct 

Italian: 
    Wrong 
Burger: 
    Correct 

Wrong: 
    Wrong 

Nothing: 
    Wrong 

當它應該是給我像

4 
Somewhat: 
    Correct 
Fuller: 
    3 
    Correct: 
    8 
    Caribbean: 
     2 
     Wrong: 
     Wrong 
     Correct: 
     Correct 
    Italian: 
     Wrong 
    Burger: 
    Correct 
    Wrong: 
    Wrong 
Nothing: 
    Wrong 

是什麼導致我的代碼有這些額外的換行符,並沒有適當的縮進?

更新

很肯定的數據是確定的。下面是一個修改版本,顯示這是確定的:

def tree_string(self, indent): 
    indentation = indent * " " 
    result = str(self.data); 
    if len(self.branches) > 0: 
     result += "[" 
     for branch in self.branches: 
     result += branch.label + ":" + branch.node.tree_string(indent + 2) + " " 
     result += "]" 
    return result 

..這使輸出

4[Somewhat:Correct Fuller:3[Correct:8[Caribbean:2[No:No Correct:Correct ] Italian:Wrong Burger:Correct ] Wrong:Wrong ] Nothing:Wrong ]

然而,縮進值,是由於某種原因,始終爲0或2

+0

您能提供一個輸入數據的例子嗎? – Krets 2013-05-04 01:11:25

+0

由於我無法打印樹,所以很難做到這一點;)。但是如果你的意思是用來產生這個的算法,那麼不是真的......它本質上是ID3,它試圖將事物分類爲「正確的」或「錯誤的」 – varatis 2013-05-04 01:12:54

+0

在第二部分的第三行是你乘以字符串 – aaronman 2013-05-04 01:13:29

回答

3

外貌像它應該對我工作:

class Tree(object): 
    def __init__(self, data): 
    self.data = data 
    self.branches = [] 
    def __str__(self): 
    return self.tree_string(0) 

    def tree_string(self, indent): 
    indentation = indent * " " 
    result = indentation + str(self.data) + "\n"; 
    for branch in self.branches: 
     result += indentation + branch.label + ": \n" + branch.node.tree_string(indent + 2) 
    return result 

class Branch(object): 
    def __init__(self, value): 
    self.label = value 
    self.node = None 

tree = Tree(4) 
b1 = Branch('Somewhat') 
b1.node = Tree('Yes') 
b2 = Branch('Fuller') 
b2.node = Tree(3) 
tree.branches = [b1, b2] 
b3 = Branch('Correct') 
b3.node = Tree(8) 
b2.node.branches = [b3] 
print(tree) 

yie lds

4 
Somewhat: 
    Yes 
Fuller: 
    3 
    Correct: 
    8 
+0

是的。數據中必然會出現一些奇怪的現象,因爲它看起來就兒童的佈局而言具有正確的結構,所以我只會進一步研究。 – varatis 2013-05-04 18:12:58