4

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

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

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 套我的套集合不是静态的。

4

3 回答 3

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
于 2013-03-21T17:44:38.800 回答
1

您可以使用itertools.combinations来获取所有可能的组合。 http://docs.python.org/2/library/itertools.html

于 2013-03-21T17:08:10.840 回答
1

我会尝试使用位掩码:

sets = [
    set([1,2,5,10,12]),
    set([1,2,6,9,12,15]),
    set([1,2,7,8,15]),
]

d = {}

for n, s in enumerate(sets):
    for i in s:
        d[i] = d.get(i, 0) | (1 << n)

for mask in range(1, 2**len(sets)):
    cnt = sum(1 for x in d.values() if x & mask == mask)
    num = ','.join(str(j) for j in range(len(sets)) if mask & (1 << j))
    print 'number of items in set(s) %s = %d' % (num, cnt)

您输入的结果:

number of items in set(s) 0 = 5
number of items in set(s) 1 = 6
number of items in set(s) 0,1 = 3
number of items in set(s) 2 = 5
number of items in set(s) 0,2 = 2
number of items in set(s) 1,2 = 3
number of items in set(s) 0,1,2 = 2
于 2013-03-21T17:50:24.457 回答