我试图在集合列表中找到集合的唯一确定子集,即集合A的子集E,使得A是包含E的唯一集合(我不确定数学如何称之为)。 例如,对于以下集合列表:
set A: {2,3,5}
set B: {2,3}
set C: {2,3,7}
set D: {3,7}
set E: {2,11,13}
set F: {2}
唯一的子集是:
set A: {5}
set B: {}
set C: {2,7}
set D: {}
set E: {{11},{13},{11,13}}
set F: {}
结果显示给定集合包含2和7的关系必须设置为C,或者如果我们只有元素3,我们就无法确定唯一集合。注意元素不一定需要是数字,它们可以是任何物体。
答案 0 :(得分:0)
不确定你在这里所做的事情的名称,但在数学上我会通过比较powersets的差异来接近它,但由于你只对子集感兴趣,然后从powerset丢弃全套(powerset是所有可能的子集,包括空集和全集)。
问题是针对其他集的powersets找到集的唯一子集。在Python中,这是通过在所有n - 1
中反复检查表示代表其他一个集合的powerset的元组列表中的[给定集合]的特定子集的元组来完成的(所以在您的示例中, 5)powersets。
这是Python中的一个实现,从包含输入的文本文件中读取:
from itertools import chain, combinations as comb
import re
def ProcessSet(l):
"""Turn a line [read from text file] into a tuple of (label, values)."""
label = l[l.find(':')-1]
vals = re.compile('{(.+)}').findall(l.rstrip())[0].split(',')
return label, vals
def GetSubsets(s):
"""
Get all subsets of a given set (including the empty set).
"""
return list(chain(*map(lambda x: comb(s, x), range(0, len(s)))))
def GetPowerset(s):
"""
Get the powerset of a given set (all subsets incl. empty and full set).
"""
return list(chain(*map(lambda x: comb(s, x), range(0, len(s)+1))))
# read the text lines into a list
with open("set_list.txt", "r") as f:
sets = [ProcessSet(l) for l in f.readlines()]
all_subsets = [GetSubsets(s[1]) for s in sets]
powersets = [GetPowerset(s[1]) for s in sets]
for i in range(0, len(sets)):
# declare label (l) and subsets (ss) for current loop iteration
l, ss = sets[i][0], all_subsets[i]
# list the other powersets to compare against
ops = [x for ind, x in enumerate(powersets) if ind != i]
# find unique subsets: those that are only a subset of the current set
# and not found in the powerset of any of the other sets
uss = list(set(ss)-set([x for y in ops for x in y if x in ss]))
#uss = []
#for s in ss:
# contains_s = [(s in ps) for ps in ops]
# if not any(contains_s):
# uss.append(s)
str_uss = ', '.join([f"({', '.join(x)})" for x in uss])
print(f"set {l}: {str_uss}")
对外输出:
set A: (3, 5), (2, 5), (5)
set B:
set C: (2, 7)
set D:
set E: (11), (2, 13), (13), (11, 13), (2, 11)
set F:
答案与你建议的答案有点不同,但它们似乎对你所描述的内容是正确的。希望有所帮助!
答案 1 :(得分:-1)
您可以将此方法用于实施。我写了一些检查方法是字符串集。
public boolean isASubset( Set<String> parent,Set<String> child) {
boolean[] result = new boolean[1];
child.forEach((String s) -> {
if (!parent.contains(s)) {
result[0] = true;
}
}
);
return result[0];
}