简体   繁体   English

实现图的邻接表

[英]implementing adjacency list for graph

I'm given a graph string like this我得到了一个这样的图形字符串

graph_string = """\
D 3
0 1
1 0
0 2
"""

and my function needs to output that graph as an adjacency list like this我的 function 需要 output 像这样的邻接列表

[[(1, None), (2, None)], [(0, None)], []]

but my function is only outputting it like this但我的 function 只是这样输出

[[(2, None)], [], []]

and i am not sure why?我不知道为什么?

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, v2, 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))    

The code is fine, except for the indentation of the final if-else.代码很好,除了最后 if-else 的缩进。 The adjacency list items need to be added immediately after an edge is processed, so that should be inside the for loop (not outside).邻接列表项需要在处理完一条边后立即添加,因此它应该在 for 循环内部(而不是外部)。

The code below is fixed.下面的代码是固定的。

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, v2, 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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM