set cover problem in python

Solutions on MaxInterview for set cover problem in python by the best coders in the world

showing results for - "set cover problem in python"
Clementine
30 Aug 2016
1def set_cover(universe, subsets):
2    """Find a family of subsets that covers the universal set"""
3    elements = set(e for s in subsets for e in s)
4    # Check the subsets cover the universe
5    if elements != universe:
6        return None
7    covered = set()
8    cover = []
9    # Greedily add the subsets with the most uncovered points
10    while covered != elements:
11        subset = max(subsets, key=lambda s: len(s - covered))
12        cover.append(subset)
13        covered |= subset
14 
15    return cover
16 
17def main():
18    universe = set(range(1, 11))
19    subsets = [set([1, 2, 3, 8, 9, 10]),
20        set([1, 2, 3, 4, 5]),
21        set([4, 5, 7]),
22        set([5, 6, 7]),
23        set([6, 7, 8, 9, 10])]
24    cover = set_cover(universe, subsets)
25    print(cover)
26 
27if __name__ == '__main__':
28    main()
29