EX_GRAPH1 = {0:[1,4,5],
1:[2,6],
2:[3],
3:[0],
4:[1],
5:[2],
6:[]
}
此函数采用有向图有向图 (表示为字典)并计算 图中节点的in-degrees。
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)
请帮助
答案 0 :(得分: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)
答案 1 :(得分:0)
您正在迭代i
x j
条目但digraph
(传入EX_GRAPH1
)不是2D数组,它是稀疏数组。< / p>
有些条目的长度为0,1,2,3个条目。
不要使用dict
。考虑numpy
和/或networkx
。