I have a Python code which finds the transitive closure.
Example:
Input: {(‘A’,’B’),(‘B’,’C’),(‘C’,’D’),(‘E’,’F’)}
Output: {(‘B’, ‘C’), (‘A’, ‘D’), (‘A’, ‘B’), (‘C’, ‘D’), (‘B’, ‘D’), (‘E’, ‘F’), (‘A’, ‘C’)}
The code works perfect, but what I’m looking for is to have the output as a set of subgraphs. I’m a beginner in Python, and I’m not sure how to do that.
According to the given input, here is the output that I’m looking for, which has two elements in the set each represents a subgraph from the transitive closure output: {(A, B, C, D), (E, F)}
Here is the code:
from collections import defaultdict
def transitive_closure(elements):
edges = defaultdict(set)
# map from first element of input tuples to "reachable" second elements
for x, y in elements: edges[x].add(y)
for _ in range(len(elements) - 1):
edges = defaultdict(set, (
(k, v.union(*(edges[i] for i in v)))
for (k, v) in edges.items()
))
return set((k, i) for (k, v) in edges.items() for i in v)
result = set(transitive_closure([('A','B'),('B','C'),('C','D'),('E','F')]))
print result
Problem solved using networkx in Python. networkx provides a functionality to find all sub-graphs of a given one.
All I needed is to have the output of the transitive_closure() method, translate it to a graph for networkx and then having the new created graph as an input to the connected_component_subgraphs() method provided by networkx.
H is a set contains all sub-graphs needed.
The main drawback is processing time, but that’s the best I could find.