邻接表和邻接矩阵在Python矩阵、Python

2023-09-10 23:16:45 作者:爱里行乞

您好我明白邻接表和矩阵的概念,但我很困惑,如何实现它们在Python:

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

这是算法来实现以下两个示例实现,但没有从一开始就为c它它们硬$ C $在其实施例知道输入:

An algorithm to achieve the following two examples achieve but without knowing the input from the start as they hard code it in their examples:

有关邻接表:

    a, b, c, d, e, f, g, h = range(8) 
    N = [ 
     {b:2, c:1, d:3, e:9, f:4},    # a 
     {c:4, e:3},                   # b 
     {d:8},                        # c 
     {e:7},                        # d 
     {f:5},                        # e 
     {c:2, g:2, h:2},              # f 
     {f:1, h:6},                   # g 
     {f:9, g:8}                    # h 
   ] 

有关邻接矩阵:

    a, b, c, d, e, f, g, h = range(8) 
    _ = float('inf') 
    #     a b c d e f g h
    W = [[0,2,1,3,9,4,_,_], # a 
        [_,0,4,_,3,_,_,_], # b 
        [_,_,0,8,_,_,_,_], # c 
        [_,_,_,0,7,_,_,_], # d 
        [_,_,_,_,0,5,_,_], # e 
        [_,_,2,_,_,0,2,2], # f 
        [_,_,_,_,_,1,0,6], # g 
        [_,_,_,_,_,9,8,0]] # h

再次任何帮助将非常AP preciated,谢谢!

Again any help will be much appreciated, Thank you!

推荐答案

假设:

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

下面是一些code的矩阵:

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

和对名单:

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}