python - 有没有办法返回布尔值以查找节点及其组件是否已连接?
问题描述
所以这是为了理解,我正在尝试编写一种方法来识别存在连接的位置,有点像节点社会。基本上,如果我输入一个矩阵和一个节点,如果给定节点具有已经相关的组件,它将返回 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 没有连接。
解决方案
我认为将您的图表设为矩阵形式会使这比需要的更难考虑。将边缘连接列表转换为连接节点列表将使事情变得更容易(并且,作为奖励,在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
推荐阅读
- angular - ngFor 完成后运行函数
- javascript - 使用 JavaScript 从 C# 检索共享点对象列表
- matplotlib - 使用相应的标签列表绘制不同颜色的点
- google-maps - 如何在 Flutter Google Map 中显示 2 LatLng 作为初始位置
- laravel - 不更新数据库也不在 laravel 中抛出错误
- angular - Angular / Ionic 4:从另一个页面返回时触发更改检测
- c# - Windows 服务中的套接字服务器在 Windows 10 上运行,但不在 Windows 服务器上
- windows - 几次重启后 KMDF DMA 传输变慢
- generics - 不安全的队列实现
- bash - 使用 sed 替换文本并缩进数据