networkx中是否有一个函数/方法来识别给定(可选加权)距离内的所有祖先/后代?
例如,有效产生与下面函数相同结果的东西?
import networkx
g = networkx.DiGraph()
edges_with_atts = [(1, 2, {'length':5}),
(1, 3, {'length':11}),
(2, 4, {'length':4}),
(2, 5,{'length':7})]
g.add_edges_from(edges_with_atts)
def descendants_within(graph, start_node=1, constraint=10, weight='length'):
result = set()
for node in networkx.descendants(graph, start_node):
if networkx.shortest_path_length(graph, start_node, node, weight) < constraint:
result.add(node)
return result
print(descendants_within(g))
#set([2, 4])
答案 0 :(得分:2)
某些NetworkX最短路径算法存在“cutoff”参数。例如,在您的情况下,您可以从源节点到所有其他节点运行“单源最短路径”计算,并将搜索限制为短于指定截止长度的路径。在下面的示例中,Dijkstra算法用于计算加权网络的最短路径。
import networkx as nx
g = nx.DiGraph()
edges_with_atts = [(1, 2, {'length':5}),
(1, 3, {'length':11}),
(2, 4, {'length':4}),
(2, 5,{'length':7})]
g.add_edges_from(edges_with_atts)
lengths = nx.single_source_dijkstra_path_length(g, source=1, weight='length', cutoff=10)
print(dict(lengths).keys())
# [1, 2, 4]