Adjacency List and Adjacency Matrix in Python

前端 未结 3 2022
感动是毒
感动是毒 2020-12-02 21:31

Hello I understand the concepts of adjacency list and matrix but I am confused as to how to implement them in Python:

An algorithm to achieve the following two examp

3条回答
  •  感动是毒
    2020-12-02 22:05

    Assuming:

    edges = [('a', 'b'), ('a', 'b'), ('a', 'c')]
    

    Here's some code for the matrix:

    from collections import defaultdict
    
    matrix = defaultdict(int)
    for edge in edges:
        matrix[edge] += 1
    
    print matrix['a', 'b']
    
    2
    

    And for the "list":

    from collections import defaultdict
    
    adj_list = defaultdict(lambda: defaultdict(lambda: 0))
    for start, end in edges:
        adj_list[start][end] += 1
    
    print adj_list['a']
    
    {'c': 1, 'b': 2}
    

提交回复
热议问题