我试图在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
您能提供一个输入数据的例子吗? – Krets 2013-05-04 01:11:25
由于我无法打印树,所以很难做到这一点;)。但是如果你的意思是用来产生这个的算法,那么不是真的......它本质上是ID3,它试图将事物分类为“正确的”或“错误的” – varatis 2013-05-04 01:12:54
在第二部分的第三行是你乘以字符串 – aaronman 2013-05-04 01:13:29