You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NetworkX的get_node_attributes时元组索引越界问题求助

问题:循环计算节点距离时触发IndexError错误

我正在调试一段Python代码,目标是根据节点位置计算哈密顿回路中节点间的距离并得出总权重。硬编码节点索引(比如0和1)时能正常得到结果,但用while循环迭代时,会触发IndexError: tuple index out of range错误。

特别说明:因为Coursera评分器会判定for _ in [:-1]这类循环索引越界(即使本地运行正常),所以改用了while循环。课程论坛活跃度极低,希望得到方向指引而非直接代码解决方案。

报错信息

C:\Users\Owner\Desktop\Math Thinking in CS\Python code>py hamilt.py
86.6083136886985
Traceback (most recent call last):
  File "C:\Users\Owner\Desktop\Math Thinking in CS\Python code\hamilt.py", line 77, in <module>
    print(cycle_length(g,cycle3))
          ^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Owner\Desktop\Math Thinking in CS\Python code\hamilt.py", line 27, in cycle_length
    dist = np.sqrt(((pos[d+1][d]-pos[d][d]))**2 + (pos[d][d+1]-pos[d+1][d+1])**2)
                                                   ~~~~~~^^^^^
IndexError: tuple index out of range

代码

import networkx as nx
import numpy as np

def cycle_length(g, cycle):
    assert len(cycle) == g.number_of_nodes()
    cycleweight = 0
    vertices = 0
    pos=nx.get_node_attributes(g,'pos')

    dist=range(0,len(cycle))
    d = 0
    while d < len(cycle) - 1:
        dist = np.sqrt(((pos[d+1][d]-pos[d][d]))**2 + (pos[d][d+1]-pos[d+1][d+1])**2) #this is the line giving me issues
        print(dist)
        d += 1
    
    while vertices < len(cycle) - 1:
        cycleweight = cycleweight + g[cycle[vertices]][cycle[vertices+1]]['weight']*dist[vertices]
        vertices += 1
    return cycleweight
    
g = nx.Graph()

g.add_node(0,pos=(174,25))
g.add_node(1,pos=(129,99))
g.add_node(2,pos=(268,212))
g.add_node(3,pos=(211,209))
g.add_node(4,pos=(156,82))

g.add_edge(4,1,weight=1)
g.add_edge(1,0,weight=1)
g.add_edge(0,3,weight=1)
g.add_edge(3,2,weight=1)
g.add_edge(2,4,weight=1)

cycle3 = [4,1,0,3,2]

print(cycle_length(g,cycle3))

已尝试操作

我试过硬编码节点索引(比如直接用pos[0][0]、pos[1][0]这类写法)能正常计算距离,但换成循环变量d后就报错。

方向指引

  • 先明确pos的结构:nx.get_node_attributes返回的是字典,键是节点编号(比如0、1、2),值是该节点的坐标元组(比如(174,25),只有x和y两个元素,索引只能是0或1)。你当前用pos[d+1][d]的写法完全错误——当d递增到2时,pos[d][d+1]就是pos[2][3],坐标元组没有索引3,必然触发索引越界。
  • 你需要计算的是回路中相邻两个节点的距离,所以应该从cycle列表中获取当前和下一个节点的编号,再去pos字典中提取对应的坐标。比如循环里当前节点是cycle[d],下一个节点是cycle[d+1],然后分别取这两个节点的x(索引0)、y(索引1)坐标来计算欧氏距离。
  • 另外,你初始化dist=range(0,len(cycle)),但在循环中把dist覆盖成了单个数值,后面第二个循环里又尝试用dist[vertices]索引取值,这也会引发错误。你应该用列表来存储每一对相邻节点的距离。

内容的提问来源于stack exchange,提问作者qiabozi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 21:14:58