generating a set from given sets such it's intersection with all the sets is different from {}

南楼画角 提交于 2021-02-04 19:44:07

问题


i have been trying to figure out an effective algorithm that returns a set such as it's intersection with the given sets isn't equal to {}.

for example : let's say the given sets are {1,7,4},{2,8,5},{1,3},{2,6} the function must return the set {1,2} because it has an intersection point with all the given sets (the generated set needs to be as small as possible)


回答1:


This is a brute force solution. Apparently, this is the well-known NP-complete problem Hitting Set.

from itertools import combinations
from collections import defaultdict

A = [{1,7,4},{2,8,5},{1,3},{2,6}]
U = set.union(*A)

result = defaultdict(list)

for i in range(1, len(U)):
    combs = combinations(U, i)
    for c in combs:
        if all(set(c) & l for l in A):
            result[len(c)].append(set(c))
    if result:
        break

result
# defaultdict(list, {2: [{1, 2}]})



回答2:


Is it necessary to make the combinedSet as small as possible? If not, this would work:

A = [{1,7,4},{2,8,5},{1,3},{2,6}]
combinedSet = set()
for a in A:
    combinedSet |= a
print(combinedSet)

Alternative, more concise method as suggested in comments:

A = [{1,7,4},{2,8,5},{1,3},{2,6}]
combinedSet = set.union(*A)
print(combinedSet)


来源:https://stackoverflow.com/questions/48726509/generating-a-set-from-given-sets-such-its-intersection-with-all-the-sets-is-dif

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!