Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subtree with networkX

In networkX, I have a tree as DiGraph().

#!/usr/bin/python
# -*- coding: utf-8 -*-
import networkx as nx
t = nx.DiGraph()
t.add_edge(1,'r')
t.add_edge(2,'r')
t.add_edge(3,'r')
t.add_edge(4,2)
t.add_edge(5,2)
t.add_edge(6,5)
print t.edges() 

If a take the node 2 of tree.
how I can get the subtree of 2 ?

Edit

I expected this subtree

[(4,2),(5,2),(6,5)]
like image 475
JuanPablo Avatar asked Dec 17 '22 08:12

JuanPablo


1 Answers

If you mean the subtree rooted at node 2, that's

from networkx.algorithms.traversal.depth_first_search import dfs_tree

subtree_at_2 = dfs_tree(t, 2)

Edit: it seems you've reversed the order of nodes in your edges. In a directed tree, all paths proceed from the root to a leaf, not the other way around. dfs_tree(t.reverse(), 2) gives you the tree that you want, but do change your code.

like image 95
Fred Foo Avatar answered Dec 27 '22 12:12

Fred Foo