首页 > 解决方案 > 有没有办法返回布尔值以查找节点及其组件是否已连接?

问题描述

所以这是为了理解,我正在尝试编写一种方法来识别存在连接的位置,有点像节点社会。基本上,如果我输入一个矩阵和一个节点,如果给定节点具有已经相关的组件,它将返回 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 没有连接。

标签: python

解决方案


我认为将您的图表设为矩阵形式会使这比需要的更难考虑。将边缘连接列表转换为连接节点列表将使事情变得更容易(并且,作为奖励,在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

推荐阅读