我正在尝试使用文本文件为有向图创建邻接表:
6 4
0 1
0 3
1 2
2 3
3 0
3 2
...,其中6是边数,4是节点数。其余各行显示的关系是0既指向1和3,又指向1指向2,依此类推...
我当前的python脚本是这样的:
def adjacency_list(file_name):
def list_duplicates_of(seq,item):
start_at = -1
locs = []
while True:
try:
loc = seq.index(item,start_at+1)
except ValueError:
break
else:
locs.append(loc)
start_at = loc
return locs
u = []
v = []
with open(file_name, "r") as fi:
for line in fi:
parts = line.split()
u.append(int(parts[0]))
v.append(int(parts[1]))
u.pop(0)
v.pop(0)
matches = []
for i in u:
temp = list_duplicates_of(u, i)
if temp not in matches:
matches.append(temp)
temp = []
for i in matches:
temp1 = []
for j in i:
x = int(v[j])
temp1.append(x)
temp.append(temp1)
return temp
哪个返回:
[[1, 3], [2], [3], [0, 2]]
在该用例中似乎工作得很好,但在其他用例中却没有。任何人都可以对可能出问题的地方有所了解吗?
谢谢!