求助修复NetworkX中n节点k度正则图生成函数问题
修复你的k-正则图生成函数
看起来你的代码是想生成一个k-正则图(每个节点度数都为指定值的图),但有几个关键问题导致它无法正常工作。我来帮你一步步修复:
原代码的核心问题
- 缺少合法性检查:k-正则图存在的前提是
amount_of_vertex * degree_of_vertex必须是偶数(因为图的总度数等于边数的2倍),同时degree_of_vertex必须小于节点数(每个节点最多只能和其他所有节点相连,度数为n-1)。 - 错误修改度数:你把
degree_of_vertex -=1,这会让最终生成的图每个节点度数比要求的少1。 - 全局变量滥用:使用全局变量
G不是好的编程实践,函数应该返回生成的图,让调用者自己处理。 - 边生成逻辑错误:循环
j的范围和邻居节点的计算方式有问题,会导致重复加边或者度数不达标。
修复后的代码
import networkx as nx import matplotlib.pyplot as plt def draw_graph(G): # 补全绘图函数的基础实现(假设你原本有这个函数) nx.draw(G, with_labels=True, node_color='lightblue', font_weight='bold') plt.show() def k_degree_graph(amount_of_vertex, degree_of_vertex): # 第一步:合法性检查,提前拦截不可能的情况 if degree_of_vertex >= amount_of_vertex: raise ValueError("每个节点的度数必须小于节点总数(不能自连或超过最大可能度数)") if (amount_of_vertex * degree_of_vertex) % 2 != 0: raise ValueError("节点数×度数必须为偶数,否则无法构建k-正则图") G = nx.Graph() nodes = list(range(1, amount_of_vertex + 1)) G.add_nodes_from(nodes) # 计算每个节点需要连接的左右邻居数量 half_degree = degree_of_vertex // 2 is_odd_degree = degree_of_vertex % 2 == 1 for node in nodes: # 连接左边的half_degree个节点(环形循环) for offset in range(1, half_degree + 1): neighbor = node - offset if neighbor < 1: neighbor += amount_of_vertex G.add_edge(node, neighbor) # 连接右边的half_degree个节点(环形循环) for offset in range(1, half_degree + 1): neighbor = node + offset if neighbor > amount_of_vertex: neighbor -= amount_of_vertex G.add_edge(node, neighbor) # 如果度数是奇数,额外连接对面的节点(此时节点数必为偶数,已通过前面的检查) if is_odd_degree: opposite_node = node + amount_of_vertex // 2 if opposite_node > amount_of_vertex: opposite_node -= amount_of_vertex G.add_edge(node, opposite_node) return G # 测试示例 if __name__ == "__main__": # 生成6个节点、每个节点度数为3的正则图 my_graph = k_degree_graph(6, 3) # 验证每个节点的度数是否符合要求 print("每个节点的度数:", {node: my_graph.degree[node] for node in my_graph.nodes()}) draw_graph(my_graph)
修复说明
- 合法性检查:提前拦截不可能构建k-正则图的情况,避免生成错误的图。
- 移除全局变量:函数返回生成的图,更灵活且符合编程规范。
- 正确的边生成逻辑:
- 当度数为偶数时,每个节点连接左右各
k/2个节点(环形连接); - 当度数为奇数时,除了左右各
(k-1)/2个节点,还要连接对面的节点(此时节点数必须是偶数,已通过前面的检查保证)。
- 当度数为偶数时,每个节点连接左右各
- 度数验证:测试代码里添加了度数验证,方便你确认每个节点的度数是否符合要求。
内容的提问来源于stack exchange,提问作者blonded04
相关产品推荐
相关产品推荐

