[英]Recursive function that print a tree
我有一个树对象:
a = <albero.Albero at 0x21fbc003cf8>
这些方法:
a.f #print out a list of sons object
[<albero.Albero at 0x21fbc003cc0>]
a.id #print out the value of a
"03"
我创建了这棵树,但现在是问题所在。 我想返回这样的输出字符串:
''' 05
_____________|_____________
| | |
02 04 06
| _________|_________
01 | | | | |
01 02 09 08 02
_|_
| |
03 06 '''
我认为只有使用递归函数才有可能。 另一个例子:
'''04
|
05
|
01
|
06
|
03'''
对于这棵树,我尝试创建此列表:
[' 80 ',' _|_ ','| | ','70 90']
有任何想法吗?
不确定你的 Albero (Tree) 类是如何设计的,所以我做了一个假的来测试。 我相信你将能够使这个功能适应你的班级:
用于测试的假树节点类:
class Albero:
def __init__(self,id,parent=None):
self.id = id
self.f = []
if parent: parent.f.append(self)
n05 = Albero("05")
n02 = Albero("02",n05)
n04 = Albero("04",n05)
n06 = Albero("06",n05)
Albero("01",n02)
Albero("01",n04)
n02 = Albero("02",n04)
Albero("09",n04)
Albero("08",n04)
Albero("02",n04)
Albero("03",n02)
Albero("06",n02)
递归函数 treeLines() 将根节点作为第一个参数,将一个获取节点的标识符和子节点的函数作为第二个参数。 这使得该函数具有通用性,并且能够处理与其自身具有父子关系的任何类。
treeText() 函数使用 treeLine() 的结果构建单个字符串,每行之间有一个行尾字符。
def treeLines(node,getInfo):
nodeId,nodeChildren = getInfo(node)
subNodes = [treeLines(child,getInfo) for child in nodeChildren]
widths = [ len(childText[0]) for childText in subNodes ]
totalWidth = sum(widths) + 2*len(widths) - 1
totalWidth = max(totalWidth,len(nodeId))
nodeLine = nodeId.center(totalWidth," ")
result = [nodeLine]
if not nodeChildren: return result
linksLine = " ".join("|".center(width," ") for width in widths)
linksLine = linksLine.center(totalWidth," ")
leftIndent = linksLine.index("|") + 1
rightIndent = linksLine[::-1].index("|") + 1
spanWidth = totalWidth - leftIndent - rightIndent - 1
leftSpan = nodeLine.index(nodeId)-leftIndent+(len(nodeId)-1)//2
rightSpan = spanWidth - leftSpan
spanLine = " "*leftIndent + "_"*leftSpan + "|" + "_"*rightSpan + " "*rightIndent
if len(nodeChildren) > 1 : result.append(spanLine)
result.append(linksLine)
maxHeight = max(len(subNode) for subNode in subNodes)
subNodes = [ subNode + [" "*len(subNode[0])]*(maxHeight-len(subNode)) for subNode in subNodes ]
result += [" ".join([subNode[i] for subNode in subNodes]).center(totalWidth," ") for i in range(maxHeight) ]
return result
def treeText(node,getInfo): return "\n".join(treeLines(node,getInfo))
print( treeText(n05,lambda n:(n.id,n.f)) )
这打印:
05
______________|______________
| | |
02 04 06
| __________|_________
01 | | | | |
01 02 09 08 02
_|_
| |
03 06
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.