从元组列表生成邻接矩阵的更优雅方法

时间:2019-05-14 16:31:25

标签: python function graph adjacency-matrix

假设我们从以元组列表表示的“友谊”图开始,

friendships = [(0, 1), (0, 2), (1, 2), (1, 3), (2,
3), (3, 4),(4, 5), (5, 6), (5, 7), (6, 8), (7, 8), (8, 9)]

其中元素0是1的朋友(因此1是0的朋友)。

我想从头开始构建邻接矩阵 ,这种方式始终适用于这种元组表示形式。

我有以下(排斥性)Python代码:

def make_matrix(num_rows,num_cols,entry_fn):
    return [[entry_fn(i,j)
             for j in range(num_cols)]
            for i in range(num_rows)]
def adjacency(connections):
    new=connections+[(x[1],x[0]) for x in connections]
    elements=list(set([x[0] for x in connections]+ [x[1] for x in connections]))
    def test(i,j):
        if (elements[i],elements[j]) in new:
            return 1
        else: return 0
    return make_matrix(len(elements),len(elements),test)

我知道它效率低下而且非常难看。有没有更聪明的方法来解决这个问题?我上面给出的示例列表的输出应为

[[0, 1, 1, 0, 0, 0, 0, 0, 0, 0],
 [1, 0, 1, 1, 0, 0, 0, 0, 0, 0],
 [1, 1, 0, 1, 0, 0, 0, 0, 0, 0],
 [0, 1, 1, 0, 1, 0, 0, 0, 0, 0],
 [0, 0, 0, 1, 0, 1, 0, 0, 0, 0],
 [0, 0, 0, 0, 1, 0, 1, 1, 0, 0],
 [0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
 [0, 0, 0, 0, 0, 1, 0, 0, 1, 0],
 [0, 0, 0, 0, 0, 0, 1, 1, 0, 1],
 [0, 0, 0, 0, 0, 0, 0, 0, 1, 0]]

更新: 根据答案之一,我有以下可能的解决方案,尽管我不知道这是否更好

def adj(connections):
    ##step 1
    temp=(set(elem[0] for elem in connections).union(
        set(elem[1] for elem in connections)))
    n=max(temp)+1
    ans=[]
    ##step 2
    for i,_ in enumerate(temp):
        ans.append([])
        for j,_ in enumerate(temp):
            ans[i].append(0)
    ##step 3
    for pair in connections:
        ans[pair[0]][pair[1]]=1
        ans[pair[1]][pair[0]]=1
    return ans

4 个答案:

答案 0 :(得分:5)

我的算法将是这样的:

  1. 查找最大顶点ID。将此称为n
  2. 创建一个n+1n+1的零数组。将此称为M
  3. 对于输入列表中的每对x, y,设置M[x][y] = 1

要提出此解决方案,我首先想到了步骤3。使用给定的输入,这似乎是填充邻接矩阵的最直接方法。但是,它需要固定大小的2D数组。因此,问题在于如何确定步骤2的n。从那里开始,不需要太多的精力就知道步骤1是什么。

细节留给读者练习。

答案 1 :(得分:1)

我不是一个Python程序员,但是......

def to_adjacency_matrix(pairs):
  size = 1 + max(map(max, pairs))
  a = [[0 for j in range(size)] for i in range(size)]
  for i, j in pairs:
    a[i][j] = a[j][i] = 1
  return a

答案 2 :(得分:0)

如果您想使用简短易懂的解决方案(并且计划以后再使用图),建议您使用networkx库。您的问题可以用双线解决:

import networkx as nx
G = nx.Graph()
G.add_edges_from(friendships)
nx.to_numpy_matrix(G)

这将返回numpy矩阵:

matrix([[0., 1., 1., 0., 0., 0., 0., 0., 0., 0.],
        [1., 0., 1., 1., 0., 0., 0., 0., 0., 0.],
        [1., 1., 0., 1., 0., 0., 0., 0., 0., 0.],
        [0., 1., 1., 0., 1., 0., 0., 0., 0., 0.],
        [0., 0., 0., 1., 0., 1., 0., 0., 0., 0.],
        [0., 0., 0., 0., 1., 0., 1., 1., 0., 0.],
        [0., 0., 0., 0., 0., 1., 0., 0., 1., 0.],
        [0., 0., 0., 0., 0., 1., 0., 0., 1., 0.],
        [0., 0., 0., 0., 0., 0., 1., 1., 0., 1.],
        [0., 0., 0., 0., 0., 0., 0., 0., 1., 0.]])

nx.adjacency_matrix(G)

这将返回scipy稀疏矩阵:

<10x10 sparse matrix of type '<class 'numpy.int64'>'
    with 24 stored elements in Compressed Sparse Row format>

答案 3 :(得分:0)

我会做的:

import numpy as np

def adjacency(connections):
    n_people = max(sum(connections, ())) + 1
    mat = np.zeros((n_people, n_people), dtype='int')
    for friend1, friend2 in connections:
        mat[friend1, friend2] = 1
        mat[friend2, friend1] = 1
    return mat

如果“从头开始”表示您不想使用numpy:

def adjacency(connections):
    n_people = max(sum(connections, ())) + 1
    mat = [[0 for _ in range(n_people)] for _ in range(n_people)]
    for friend1, friend2 in connections:
        mat[friend1][friend2] = 1
        mat[friend2][friend1] = 1
    return mat