2014-08-28 73 views
-2
EX_GRAPH1 = {0:[1,4,5], 
     1:[2,6], 
     2:[3], 
     3:[0], 
     4:[1], 
     5:[2], 
     6:[] 
     } 

该函数采用一个有向图有向图 (表示为字典),并计算 中度在图中的节点。IndexError:列表索引超出范围(它必须是字典,而不是列表)

def compute_in_degrees(digraph): 
in_degrees = {} 
i = 0 
j = 0 
matches = [] 
while i < len(digraph): 
    m = 0 
    while j < len(digraph): 
     if digraph[i][j] == i: <--- HERE IndexError: list index out of range 
      j += 1 
      m += 1 
      matches.append(m) 
     else: 
      j += 1 
    in_degrees[i] = matches 
    i += 1 
return in_degrees 
print compute_in_degrees(EX_GRAPH1) 

帮助,请

+1

这应该是'while j jonrsharpe 2014-08-28 14:54:23

回答

0

尝试:

while j < len(digraph[i]): 

目前,你只是在重复循环的i,所以你可能会超支。或者,如@jonrsharpe在评论中说,使用for循环:

def compute_in_degrees(digraph): 
    in_degrees = {} 
    i = 0 
    j = 0 
    matches = [] 
    for i, sublist in enumerate(digraph): 
     m = 0 
     for j in sublist: 
      if j == i: 
       m += 1 
       matches.append(m) 
     in_degrees[i] = matches 
    return in_degrees 
print compute_in_degrees(EX_GRAPH1) 
0

你迭代i X j项,但digraphEX_GRAPH1传递中)是不是一个二维数组,它是一个稀疏数组。

部分条目为0,1,2,3条目。

请勿使用dict。考虑numpy和/或networkx

相关问题