This problem is known as MINIMUM k-UNION, and it is NP-hard , as shown below:
, , .
, , : , . : , , . Python:
def small_union(sets, k):
"""
Choose `k` elements from `sets` and return their union. Attempt
to return a fairly small union using a greedy approach.
>>> small_union([{1,2}, {2,3}, {1,2,3}, {1}, {2}], 3)
set([1, 2])
>>> small_union([{1,2}, {2,3}, {3,4}, {1,4}], 3)
set([1, 2, 3, 4])
"""
union = set()
for _ in xrange(k):
s = min(sets, key = lambda s: len(s | union))
sets.remove(s)
union |= s
return union