问题
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