python - 在 NetworkX 中检查子图是否为集团的最快方法
问题描述
我想知道 G 的给定子图是否是完整图。我期待找到一个内置函数,例如is_complete_graph(G)
,但我看不到任何类似的东西。
我目前的解决方案是创建一个新的辅助函数:
def is_complete(G):
n = G.order()
return n*(n-1)/2 == G.size()
我想这可能很快,但我觉得自己实施这种事情是错误的,而且我觉得在 NetworkX 中必须有一种“正确”的方式来做到这一点。
我只需要简单无向图的解决方案。
解决方案
编辑
底部的答案比较干净。但是,似乎以下方法更快:
def is_subclique(G,nodelist):
H = G.subgraph(nodelist)
n = len(nodelist)
return H.size() == n*(n-1)/2
我不得不承认,我并不完全明白。但显然创建子图比检查每条边是否存在要快。
较慢的替代方案我预计会更快:
我们将检查是否所有的边缘都在那里。我们将用于combinations
生成我们检查的对。请注意,如果combinations
返回(1,2)
,则不会返回(2,1)
。
from itertools import combinations
import networkx as nx
def is_subclique(G, nodelist):
r'''For each pair of nodes in nodelist whether there is an edge
if any edge is missing, we know that it's not a subclique.
if all edges are there, it is a subclique
'''
for (u,v) in combinations(nodelist,2): #check each possible pair
if not G.has_edge(u,v):
return False #if any edge is missing we're done
return True #if we get to here, then every edge was there. It's True.
G = nx.Graph()
G.add_edges_from([(1,2), (2,3), (3,1), (4,1)])
is_subclique(G, [1,2,3])
> True
is_subclique(G, [1,4])
> True
is_subclique(G, [2,3,4])
> False
推荐阅读
- html - GitHub存储库首页上的PDF?
- nginx - 在不提供凭据的情况下允许来自 IP 的请求访问 Nginx 失败
- jmeter - JMeter 中的 SameSite cookie
- angular - 使用 angular 9 和 ngrx 进行表单数据编辑,引发错误
- flutter - 连续多个 WidgetSpan 不考虑方向性
- python - Django 只能通过命令行运行,但不能在 PyCharm 中运行
- vba - VBA:在 Word 中的拼写错误旁边编写拼写建议
- python-3.x - Pyglet 3.7 中的 Sprite 子类化
- python - 在 python 中手动创建训练和测试数据集
- woocommerce - Woocommerce 基于产品变体属性的新订单电子邮件的附加收件人