【发布时间】:2014-01-10 12:23:49
【问题描述】:
我的 python 代码当前打印出 k-ary 树中每个节点的名称,从根到叶。但是,我希望将子节点 > 1 的分支节点的名称打印 n 次;其中 n = 孩子的数量。
对于上面的树
我的代码打印以下内容
start
a
b
d
f
end
c
e
end
c
e
end
但是,我希望它打印以下内容
start
a
b
d
f
end
b
c
e
end
d
c
e
end
我希望节点 b 和 d 打印两次(以正确的顺序),因为它们有两个孩子。
我觉得这比我想象的要简单。我需要添加访问过的节点列表吗?但是我还需要知道访问的次数?
需要注意的是,只有具有 (n.tag == prefix + 'decision' 或 n.tag == prefix + 'task') 的节点才会有多个子节点。因此,我可以保留一个决策/任务节点列表以及它们被访问的次数。如果访问次数==子节点数,从列表中弹出节点?
我觉得我把这件事复杂化了很多。
这是一个简单的示例,但是我的代码需要适用于 k-ary。 (我知道我的示例树只是二叉树)。
我的代码如下:
from itertools import izip
import xml.etree.ElementTree as ET
def main():
prefix = "{http://jbpm.org/4.4/jpdl}"
xml = ET.parse("testWF2.xml")
root = xml.getroot()
i = root.findall('*')
# convert list to dictionary indexed by Element.name
temp = []
for it in i:
name = it.get("name")
if (name):
temp.append(name)
else:
tag = it.tag
temp.append(tag.replace(prefix, '')) # if no name exists use tag (ex. start and end)
b = dict(izip(temp, i)) # create the dictionary with key = name
nodes = []
# add root to the list
nodes.append(b["start"])
while(nodes):
n = nodes.pop()
transitions = n.findall(prefix+"transition")
children = []
# get all of n's children
for t in transitions:
children.append(b[t.get("to")])
for child in children:
nodes.append(child) # add child
if (not n.get("name")):
print ("start")
else:
print(n.get("name"))
# end while loop
main()
如果有人需要查看 testWF2.xml 文件,请在此处粘贴 http://bpaste.net/show/160832/
【问题讨论】:
-
感谢您提供足以使用它的 xml 文件和代码。顺便说一句,你为什么要双重列出父母?如果是为了消除歧义,您真的需要列出从根目录开始的整个路径,不是吗?
标签: python algorithm python-2.7 tree tree-traversal