【发布时间】:2019-05-14 16:31:24
【问题描述】:
假设我们从一个由元组列表表示的“友谊”图开始,
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
【问题讨论】:
-
你提前知道顶点的数量吗?
-
@Code-Apprentice no,这是挑战的一部分,也是我在中间有这个粗略元素定义的原因
-
从头开始 - 这是否意味着您实际上只在寻找原生解决方案而库不在?
-
@ParitoshSingh 是的。我对具有可以调用的邻接函数的图形/网络库不感兴趣。
标签: python function graph adjacency-matrix