pythonpygraphviz

How to use nested tuples to draw graphviz digraph in Python?


I want to draw Digraph of graphviz by using a nested tuples:

nested = (("2","3"),("5", "6"))

How to process nested to get the next result?

from graphviz import Digraph
edges = [("1","2"),("1","3"),("4","5"),("4","6"), ("0", "1"), ("0", "4")]
graph = Digraph()
graph.edges(edges)
graph

enter image description here


Solution

  • I suspect that this can be done more efficiently, but here's one way to get those edges. I assume that the actual elements of the tuple are irrelevant and that what you're actually after is the place of the element within the hierarchy of nested tuple.

    def dfs_order(tup):
        if not isinstance(tup,tuple):
            return [tup]
        ans = [tup]
        for t in tup:
            ans.extend(dfs_order(t))
        return ans
    
    def to_edges(tup, label):
        if not isinstance(tup,tuple):
            return []
        ans = []
        for c in tup:
            ans.append((label[tup],label[c]))
            ans.extend(to_edges(c,label))
        return ans
    
    
    nested = (("2","3"),("5", "6"))
    label = {t:str(i) for i,t in enumerate(dfs_order(nested))}
    edges = to_edges(nested,label)