I use a python NetworkX graph. How to check if 2 nodes are disconnected and then get a new version of the graph where these 2 nodes are connected.
The difference between 2 graphs should have min edit distance (Levenshtein distance)
Before and after for nodes=[1,2]
:
Advertisement
Answer
JavaScript
x
18
18
1
import networkx as nx
2
3
G = nx.DiGraph([(1, 1), (2, 3), (4, 3)])
4
5
6
def check_edge(source, target):
7
if not G.has_edge(source, target):
8
print('adding edge between {} and {}'.format(source, target))
9
G.add_edge(source, target)
10
else:
11
print('edge exists between {} and {}'.format(source, target))
12
13
14
check_edge(1, 2)
15
# adding edge between 1 and 2
16
check_edge(1, 2)
17
# edge exists between 1 and 2
18
you can also have a condition to check for an edge of either direction with:
JavaScript
1
2
1
if not G.has_edge(source, target) and not G.has_edge(target, source):
2