问题描述
我得到了一个这样的图形字符串
graph_string = """\
D 3
0 1
1 0
0 2
"""
[[(1,None),(2,None)],[(0,[]]
[[(2,[],[]]
我不知道为什么?
def adjacency_list(graph_str):
"""Takes a graph string and returns the adjacency list"""
lines = graph_str.splitlines()
header = lines[0].split()
if len(header) > 2:
graph_type,vertices,weight = header[0],header[1],header[2]
else:
graph_type,vertices = header[0],header[1]
weight = None
edges = lines[1:]
adj_list = [[] for _ in range(int(vertices))]
if len(edges) > 0:
for edge in edges:
if weight == 'W':
v1,v2,w = edge.split()
v1,w = int(v1),int(v2),int(w)
else:
v1,v2 = edge.split()
v1,v2 = int(v1),int(v2)
w = None
if graph_type == 'U':
adj_list[v1] += [(v2,w)]
adj_list[v2] += [(v1,w)]
else:
adj_list[v1] += [(v2,w)]
return adj_list
graph_string = """\
D 3
0 1
1 0
0 2
"""
print(adjacency_list(graph_string))
解决方法
代码没问题,除了最后一个 if-else 的缩进。邻接表项需要在处理完一条边后立即添加,因此应该在for循环内(而不是在外)。
下面的代码是固定的。
def adjacency_list(graph_str):
"""Takes a graph string and returns the adjacency list"""
lines = graph_str.splitlines()
header = lines[0].split()
if len(header) > 2:
graph_type,vertices,weight = header[0],header[1],header[2]
else:
graph_type,vertices = header[0],header[1]
weight = None
edges = lines[1:]
adj_list = [[] for _ in range(int(vertices))]
if len(edges) > 0:
for edge in edges:
if weight == 'W':
v1,v2,w = edge.split()
v1,w = int(v1),int(v2),int(w)
else:
v1,v2 = edge.split()
v1,v2 = int(v1),int(v2)
w = None
if graph_type == 'U':
adj_list[v1] += [(v2,w)]
adj_list[v2] += [(v1,w)]
else:
adj_list[v1] += [(v2,w)]
return adj_list
graph_string = """\
D 3
0 1
1 0
0 2
"""
print(adjacency_list(graph_string))