python - 当且仅当图保持连接时从nx图中删除节点?
问题描述
当且仅当图保持连接时,我试图从现有的 nx 图 G 中删除节点。最有效的方法是什么?
例如,我尝试删除节点 5 是:
node = 5
# make temporary copy
T = G.copy()
# remove node from copy
T.remove_node(node)
# replace G with T if the graph is connected
if nx.is_connected(T):
G = T
我只是犹豫是否要创建副本来执行此操作,因为我正在迭代地从大图中删除节点。有一个更好的方法吗?
解决方案
您可能忽略了Graph.copy()可用的单个参数,即Graph.copy(as_view = False)
。该参数的作用是提供“原始结构的副本,而不需要任何内存来复制信息”。您可以在该模拟结构上执行删除,并在保留完整连接后,在真实物体上执行它。如果您担心存储两个完整网络的内存阻塞,那么使用该参数可能是您的解决方案。如果没有,您需要在问题中提供更多详细信息和一些可重现的代码。
import networkx as nx
import time as t
base_graph = nx.circulant_graph(n=1000, offsets=[1])
if nx.is_connected(base_graph):
print('Graph is connected.')
node_id_to_remove = 500
start_time = t.time()
copied_real_graph = base_graph.copy(as_view=False)
print(f"Execution Time: {(t.time() - start_time)}")
start_time = t.time()
copied_view_graph = base_graph.copy(as_view=True)
print(f"Execution Time: {(t.time() - start_time)}")
-------------------
Graph is connected.
Execution Time: 0.005429983139038086
Execution Time: 0.0003299713134765625
推荐阅读
- xslt - 需要汇总数据可以为空的节点
- r - Bash 菜单脚本 - 无法执行命令
- java - 无法解析符号“CollectNewspaperKarel”
- pci-compliance - 我可以在没有 PCI 合规性的情况下存储用户银行详细信息吗?
- jquery - 如何使用 jQuery 3.3.1 设置选择列表的选项
- c# - 条件表达式中的数据类型不匹配 ms-access c#
- hive - Hive INSERT OVERWRITE 不适用于启用 ACID 属性
- python - 连接到 mysql wamp 和 django 的问题?
- sql-server - 使用触发器仅插入或更新特定记录
- javascript - 浏览器中的 Javascript 文件是否需要 .js 扩展名?