import copy
import matplotlib.pyplot as plt
import networkx as nx
def vew_graph(lst_node_edge):
gAnt = nx.Graph()
# gAnt.add_edges_from(lst_node_edge)
gAnt.add_weighted_edges_from(lst_node_edge)
labels = nx.get_edge_attributes(gAnt, “weight”)
plt.axis(‘off’)
nx.draw_networkx(gAnt,
pos=nx.spring_layout(gAnt, seed=0),
node_size=600,
cmap=‘coolwarm’,
font_size=14,
font_color=‘white’
)
nx.draw_networkx_edge_labels(gAnt, pos=nx.spring_layout(gAnt, seed=0), edge_labels=labels)
return gAnt
def del_edgenode_shortest_weighted_path(gAnt, lst_del_edge):
# 使用 remove_node(n) 删除指定顶点 n,remove_edge(u,v) 删除指定的边 (u,v)。
# 使用 remove_nodes_from([n1,…nk]) 删除多个顶点,remove_edges_from([(u1,v1),…(uk,vk)]) 删除多条边。
path_lenth = []
for del_edge in lst_del_edge:
new_gAnt = copy.deepcopy(gAnt)
source, target, weight = del_edge
new_gAnt.remove_edge(source, target)
minWPath = nx.dijkstra_path(new_gAnt, source=source, target=target, weight='weight')
lMinWPath = nx.dijkstra_path_length(new_gAnt, source=source, target=target, weight='weight')
print(f'source = {source}, target = {target}')
print("S 到 E 的最短加权路径: ", minWPath)
print("S 到 E 的最短加权路径长度: ", lMinWPath)
if lMinWPath != 0:
path_lenth.append(del_edge)
return path_lenth
if name == “main”:
lst_del_edge = []
lst_node_edge = [(‘a’, ‘b’, 0),(‘a’, ‘c’, 0),(‘b’, ‘c’, 0.8)]
# lst_node_edge = [(‘a’, ‘b’, 0),(‘a’, ‘c’, 0.7),(‘b’, ‘c’, 1.8)]
# lst_node_edge = [(‘a’, ‘b’, 1.2),(‘a’, ‘c’, 2.6),(‘b’, ‘c’, 1.4),
# (‘b’, ‘d’, 1.7),(‘c’, ‘d’, 3.4)]
group_id = ‘a’
error_group = []
for node_edge in lst_node_edge:
source, target, weight = node_edge
if weight < 2 and weight > 0:
lst_del_edge.append(node_edge)
gAnt = vew_graph(lst_node_edge)
lst_del_edge_length = del_edgenode_shortest_weighted_path(gAnt, lst_del_edge)
if lst_del_edge_length:
error_group.append(group_id)
print(error_group)