python-3.x - 找到q-松弛交集的算法或Python函数?
问题描述
我正在寻找一种“更快”的方法来查找集合列表的q-relaxed 交集。我目前已经实现了以下 Python 函数,但速度很慢。我希望这适用于约 100 套和 q=10。有什么聪明的主意吗?
def relaxed_intersection(*sets, q=0):
"""
This function finds the q-relaxed intersection set of the sets supplied in
*sets as a list.
We first find the intersection of subsets formed by leaving q sets out and
then find the union of these intersetions.
"""
import itertools
n = len(sets)
#form subsets leaving q sets out
combinations = list(itertools.combinations(sets, n-q))
#find the intersection of all the subsets
intersections = [set() for i in range(len(combinations))]
for i, comb in enumerate(combinations):
intersections[i] = set.intersection(*comb)
#find the union of all the intersections
q_relaxed_set = set.union(*intersections)
return q_relaxed_set
解决方案
只需检查每个元素是否至少是n - q
集合的一部分。
from collections import Counter
def relaxed_intersection(*sets, q=0):
"""
This function finds the q-relaxed intersection set of the sets supplied in
*sets as a list.
"""
counter = Counter(x for s in sets for x in set(s))
n = len(sets)
return {x for x, c in counter.items() if c >= n - q}
推荐阅读
- sql - 是否可以在不使用 SQL 连接的情况下对不同年份进行每周比较?
- mongodb - $group 与 mongodb 中的嵌套数组
- javascript - Vue.js 将对象传递给其他组件
- selenium - Selenium/Testng:如果发生异常,则跳过或失败其余的 @Test
- angular - 具有 DomSanitizer 依赖项的 Angular 6 单元测试组件
- android - 使用 BroadcastReceiver 获取 rssi 值
- docker - 命令不在 docker-compose.yml 中执行
- c# - C#:复制文件夹中的多个文件并保留文件夹结构
- apache-spark - 将密钥分配给 pyspark rdd 中的所有值
- html - 从顶部对齐 li 项目