识别树的叶子和祖先 - Python

时间:2018-03-29 08:50:25

标签: python-3.x tree networkx

我有一棵树,如下所示:

enter image description here

我需要找到叶子,使它们具有相同的祖先。例如,在上面的树中,我们有两个具有相同祖先的节点。有人可以建议我这样做吗?

在这两个答案的帮助下,我尝试以下方法找到具有共同父级的叶子对,然后我需要加入这两个叶子并更新树。但是,这没有给我正确的叶子对,并没有正确更新树。你能否在这里找到错误并帮助我?

def common_parent(T, n1, n2):
for n1 in N:
    for n2 in N:
        if T.neighbors(n1) == T.neighbors(n2):
            return (n1, n2)

nodes_pairs = []
for n1 in N:
    for n2 in N:
        if n1 != n2 and common_parent(T, n1,n2):
            nodes_pairs.append(common_ancestor(T, n1,n2))
print(nodes_pairs)

for n1 in N:
        for n2 in N:
            if T.neighbors(n1) == T.neighbors(n2):
                T.add_edge(n1, n2, weight='distance')
print(T.edges())

2 个答案:

答案 0 :(得分:1)

查找具有共同祖先的节点

创建树

G = nx.balanced_tree(2, 2, create_using=None)

绘制

pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos)
nx.draw_networkx_edges(G,pos)
nx.draw_networkx_labels(G,pos, font_color='w')
plt.axis('off')
plt.show()

tree

def common_ancestor(G, n1, n2):
    if nx.shortest_path_length(G, n1, n2) == 2:
        return (n1, n2)

nodes_pairs = []
for n1 in G.nodes():
    for n2 in G.nodes():
        if n1 != n2 and common_ancestor(G, n1,n2):
            nodes_pairs.append(common_ancestor(G, n1,n2))
nodes_pairs

[OUT]:

[(0, 3),
 (0, 4),
 (0, 5),
 (0, 6),
 (1, 2),
 (2, 1),
 (3, 0),
 (3, 4),
 (4, 0),
 (4, 3),
 (5, 0),
 (5, 6),
 (6, 0),
 (6, 5)]

答案 1 :(得分:1)

可以这样做:

import networkx as nx
import matplotlib.pyplot as plt
from collections import defaultdict

G = nx.Graph()

## setup, borrowed from https://necromuralist.github.io/data_science/posts/distance-in-social-networks/
left = tuple("AAKBCCFEDEIE")
right = tuple("KBBCFEGFEIJH")
G.add_edges_from(list(zip(left, right)))
## 

# retrieve nodes of degree=1 
k1corona = list(nx.k_corona(G, 1)) 
# and their parents
nodes = { node: list(G[node])[0]  for _set in k1corona for node in _set }

# counting leaves for each parent
parents = defaultdict(int)
for node,parent in nodes.items():
  parents[parent]+=1

# filtering out loners
leaves = [ node for node,parent in nodes.items() if parents[parent]>=2 ] 

# drawing
pos = nx.spring_layout(G,random_state=0)
nx.draw_networkx(G, pos=pos, with_labels=True)
nx.draw_networkx_nodes(G.subgraph(leaves), pos=pos, with_labels=True, node_color='blue')
plt.show()

enter image description here