这是为了理解,我正在尝试编写一种方法来识别存在连接的地方,有点像节点社会。基本上,如果我输入一个矩阵和一个节点,如果给定节点具有已经相关的组件,它将返回True或False。
我尝试使用while循环遍历访问的集,但是我仍然迷失在过程中。就理解而言,我对for循环感到更自在。如果有一种方法可以迭代子矩阵列表以找到易于理解和适应的节点之间的关系。
def society(graph_matrix, node):
for item in (graph_matrix):
for j in item:
if graph_matrix[item][j] and graph_matrix[item][node] and graph_matrix[j][node] == 1:
return True
return False
gmatrix = [ [0,1,1,1,0],
[1,0,0,1,0],
[1,0,0,0,1],
[1,1,0,0,0],
[0,0,1,0,0] ]
因此,如果我输入(society(gmatrix,0))
,答案应该返回True
,因为当您查看节点0时,可以看到其与节点1和节点3的连接,而节点1与节点3的连接如下:可以在gmatrix矩阵中观察到。有点像节点社会。我是
但是,society(gmatrix,2)
应该返回False
,节点2连接到0,并且4而不连接0和4。
答案 0 :(得分:1)
我认为,以矩阵形式显示图形会使思考比实际需要的难。转换边缘连接列表,使其成为连接节点的列表将使事情变得更容易(此外,如果society()
返回False
,则减轻计算负担,这对于节点数增加):
def to_map(gmatrix):
return [[k for k,v in enumerate(edges) if v] for edges in gmatrix]
那么您将能够做到:
def society(graph_map, node):
for n in graph_map[node]:
if n == node:
continue
for nn in graph_map[n]:
if nn != node and nn != n and nn in graph_map[node]:
return True
return False
如:
gmatrix = [ [0,1,1,1,0],
[1,0,0,1,0],
[1,0,0,0,1],
[1,1,0,0,0],
[0,0,1,0,0] ]
gmap = to_map(gmatrix)
print(society(gmap,0)) # True
print(society(gmap,2)) # False
答案 1 :(得分:1)
在您的代码for item in (graph_matrix):
中,此处item
代表数字列表。
而且,您不能将数字列表用作像这样的矩阵索引:graph_matrix[item][node]
。
据我了解您的问题,您想知道三个节点是否互连。为此,您可以通过以下方式修改代码:
def society(graph_matrix, node):
for i in range(len(graph_matrix[node])):
for j in range(len(graph_matrix[node])):
if graph_matrix[node][i] and graph_matrix[node][j] and graph_matrix[i][j] == 1:
return True
return False
gmatrix = [ [0,1,1,1,0],
[1,0,0,1,0],
[1,0,0,0,1],
[1,1,0,0,0],
[0,0,1,0,0] ]
print(society(gmatrix, 0));
在这里,len(graph_matrix[node])
将返回graph_matrix[node]
的长度,而range(len(graph_matrix[node]))
将从 0 迭代为 length- 1 。