如果断开连接,如何连接两个节点

How to connect two nodes if they are disconnected

我使用 python NetworkX 图。如何检查 2 个节点是否断开连接,然后获取这 2 个节点连接的图形的新版本。

2 个图之间的差异应该有最小编辑距离(Levenshtein distance

nodes=[1,2] 前后:

|

import networkx as nx

G = nx.DiGraph([(1, 1), (2, 3), (4, 3)])


def check_edge(source, target):
    if not G.has_edge(source, target):
        print('adding edge between {} and {}'.format(source, target))
        G.add_edge(source, target)
    else:
        print('edge exists between {} and {}'.format(source, target))


check_edge(1, 2)
# adding edge between 1 and 2
check_edge(1, 2)
# edge exists between 1 and 2

您还可以有一个条件来检查任一方向的边缘:

if not G.has_edge(source, target) and not G.has_edge(target, source):