gpt4 book ai didi

python - 计算集合列表中所有组合的交集

转载 作者:太空狗 更新时间:2023-10-30 02:47:51 25 4
gpt4 key购买 nike

我有一套集合。我想找到仅在每个集合组合的交集中找到的项目数。我基本上想做与在维恩图中创建数字相同的事情。

一个基本的例子可能会更清楚。

a = set(1,2,5,10,12)
b = set(1,2,6,9,12,15)
c = set(1,2,7,8,15)

我应该以仅在以下位置找到的项目数结束:

  • 一个
  • b
  • c
  • a和b的交集
  • a和c的交集
  • b和c的交集
  • a、b、c的交集

一种不可扩展的方式是

num_a = len(a - b - c)  # len(set([5,10])) -> 2
num_b = len(b - a - c) # len(set([6,9])) -> 2
num_c = len(c - a - b) # len(set([7,8])) -> 2

num_ab = len((a & b) - c) # 1
num_ac = len((a & c) - b) # 0
num_bc = len((b & c) - a) # 1

num_abc = len(a & b & c) # 2

虽然这适用于 3 组,但我的集合不是静态的。

最佳答案

IIUC,这样的事情应该可行:

from itertools import combinations

def venn_count(named_sets):
names = set(named_sets)
for i in range(1, len(named_sets)+1):
for to_intersect in combinations(sorted(named_sets), i):
others = names.difference(to_intersect)
intersected = set.intersection(*(named_sets[k] for k in to_intersect))
unioned = set.union(*(named_sets[k] for k in others)) if others else set()
yield to_intersect, others, len(intersected - unioned)


ns = {"a": {1,2,5,10,12}, "b": {1,2,6,9,12,15}, "c": {1,2,7,8,15}}
for intersected, unioned, count in venn_count(ns):
print 'len({}{}) = {}'.format(' & '.join(sorted(intersected)),
' - ' + ' - '.join(sorted(unioned)) if unioned else '',
count)

给出

len(a - b - c) = 2
len(b - a - c) = 2
len(c - a - b) = 2
len(a & b - c) = 1
len(a & c - b) = 0
len(b & c - a) = 1
len(a & b & c) = 2

关于python - 计算集合列表中所有组合的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15553728/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com