Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 如何在图表中显示直径?_Python 3.x_Networkx_Graph Theory - Fatal编程技术网

Python 3.x 如何在图表中显示直径?

Python 3.x 如何在图表中显示直径?,python-3.x,networkx,graph-theory,Python 3.x,Networkx,Graph Theory,我有一个完整的图G,有5个节点,我必须找到G的直径(随机选择的节点),并用红色绘制这个直径。如何使用Networkx和Python实现这一点?这些是我的尝试。我还需要说明的是,它们的数量更多,但唯一的区别是,我没有使用最短路径,而是尝试使用其他函数(子图、算法等)。此外,我需要解释随机节点意味着随机选择直径的起点 import networkx as nx #1 attempt G = nx.complete_graph(5) dg = nx.shortest_path(G) edge_

我有一个完整的图G,有5个节点,我必须找到G的直径(随机选择的节点),并用红色绘制这个直径。如何使用Networkx和Python实现这一点?这些是我的尝试。我还需要说明的是,它们的数量更多,但唯一的区别是,我没有使用最短路径,而是尝试使用其他函数(子图、算法等)。此外,我需要解释随机节点意味着随机选择直径的起点

import networkx as nx  #1 attempt

G = nx.complete_graph(5)

dg = nx.shortest_path(G)

edge_colors = ['red' if e in dg.edges else 'black' for e in G.edges]

nx.draw(G, edge_color=edge_colors)






def get_diameters(graph):   #attempt 2


diams = []
for g in nx.connected_component_subgraphs(graph):
    diams.append(nx.diameter(g))
diams = list(filter(lambda a: a != 0, diams))
return np.array(diams) Graph.number_of_nodes()

我理解你的问题,你不是在寻找图本身的直径,而是在给定一个随机起始节点的图中寻找最长最短路径。这可以通过使用
nx.shortest_path
source
关键字参数来实现,给它一个随机的起始节点。我们可以查看结果字典,找到最长最短路径,并用红色绘制形成此路径的边

代码 输出 注意,在本例中,图形的直径为4;最长最短路径是从节点6到节点4。随机选择的源节点为7-从节点7开始的最长最短路径长度为3


请显示您的尝试。另外,请解释“随机选择的节点”是什么意思。图的直径不取决于选择的节点。是的,它不取决于选择的节点。但当你需要绘制它时,它很重要,就像我在随机(不完整)图中所做的一样,随机选择的节点不一定属于最长的测地线之一。这是真的,但是我需要找到一个算法,可以找到直径并在图表上显示,所以在这个特殊任务中,我应该将其随机化。为了澄清,你的任务是选择一个随机节点,然后找到从该节点到另一个节点的最长最短路径,并将这些边画成红色?完整图形的预期输出是什么?以红色绘制随机边?
import networkx as nx
import random

# Create graph
G = nx.fast_gnp_random_graph(10, 0.3)

# Pick a random node
source = random.choice(list(G.nodes))

# Find the longest shortest path from the node
shortest_paths = nx.shortest_path(G, source=source)
target = max(shortest_paths, key=lambda i: len(shortest_paths[i]))
l_s_path = shortest_paths[target]
l_s_path_edges = list(zip(l_s_path, l_s_path[1:]))

# Draw the graph, then draw over the required edges in red.
pos = nx.spring_layout(G)
nx.draw(G, pos=pos, with_labels=True)
nx.draw_networkx_edges(G, edge_color='r', edgelist=l_s_path_edges, pos=pos)