2013-05-04 57 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