邻接表和邻接矩阵在Python [英] Adjacency List and Adjacency Matrix in Python

查看:3857
本文介绍了邻接表和邻接矩阵在Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我明白邻接表和矩阵的概念,但我很困惑,如何实现它们在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}

这篇关于邻接表和邻接矩阵在Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆