[英]Generic Tree in Recursion in Python
我对 Python 很陌生,并被困在通用树中。
我有 2 列。 假设名称为 A 和 B。现在事情是 A 列的值是 B 列中相应值的父级。现在再次在 A 列中搜索 B 列的值。现在它成为父级,其相应值成为子级.
例如:
A B
--------
1 2
5 3
2 5
3
现在这里是值“1”。
1 是父母。 2 是 1 的孩子。现在再次在 A 列中搜索 2。这现在使 2 成为父母,5 成为孩子。 现在我们再次搜索它给了我们值 3 。 3 也是一样,但是 3 前面没有值,所以树在这里结束,3 是树的叶节点。 在示例中,我显示了每个父节点的一个子节点,但在我的数据集中,每个父节点可以有多个子节点,并且树会一直运行直到到达所有叶节点。 我知道递归是这里的解决方案,但如何解决?
我在输出中需要的是与父级的所有可能集。 在这种情况下 [1,2], [1,2,5], [1,2,5,3]。 此外,如果 1 有 2 个孩子,我们假设 2 和 4。
那么 [1,2,4] 也会被算作一个集合。 这里有什么帮助吗? 我真的很努力!
Venky = {}
def Venkat(uno):
x = df[df.ColA == uno]
data = list(zip(x['ColB'],x.ColA))
Venky[uno] = Node(uno)
for child,parent in data:
Venky[child] = Node(child, parent=Venky[uno])
print(Venky[child])
y = df[df['ColA'] == (Venky[child]).name]
if (y['ColB'].empty == False):
data = list(zip(y['ColB'],y.ColA,))
#y_unique = y['ColB'].unique()
for k in y['ColB']:
res = Venkat(k)
return res
udo = 'a'
Venkat(udo)
for pre, fill, node in RenderTree(Venky[udo]):
print("%s%s" % (pre, node.name))
以上是我的示例代码。 df 是我的 colA 和 colB 数据框。 ColA 是 A 列,colB 是相同的。 我还为此代码导入了 Anytree 和 pandas 库。 我得到的结果是这样的:
Node('/1/2')
Node('/4/nan')
1
└── 2
Node('/1/2')
Node('/4/nan')
None
这里 4 是树中 2 的兄弟,即 1 有 2 个孩子,这里 2 和 4 与数据集不同。 但目前我不关心输出。 我现在想建一棵树。 然后我会玩弄输出。
我会建议一个解决方案,您首先将表结构转换为字典,为每个节点(字典键)提供子节点(字典值)列表。
然后执行深度优先遍历该树,使用递归,使用新访问的子节点扩展路径。 输出每个阶段的路径。 为此,发电机是理想的解决方案。
代码:
def all_paths(table, root):
# convert table structure to adjacency list
children = {}
for node, child in table:
if child:
children[node] = children.setdefault(node, []) + [child]
# generator for iteration over all paths from a certain node
def recurse(path):
yield path
if path[-1] in children:
for child in children[path[-1]]: # recursive calls for all child nodes
yield from recurse(path + [child])
return recurse([root])
# Sample data in simple list format
table = [
[1, 2],
[5, 3],
[2, 5],
[2, 6],
[2, 4],
[6, 7],
]
# Output all paths from node 1
for path in all_paths(table, 1):
print(path)
以上输出:
[1]
[1, 2]
[1, 2, 5]
[1, 2, 5, 3]
[1, 2, 6]
[1, 2, 6, 7]
[1, 2, 4]
看到它在repl.it 上运行
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.