Search code examples
pythonpython-3.xlistnested-lists

How can you remove superset lists from a list of lists in Python?


I have a list of lists in Python like the following:

[[1,2,3],[2,3],[2,4,3],[4,5],[5]]

I want to remove all the inner lists that are a superset (a list that contain all the elements of another list, but with additional elements) of another inner list. For the example above, removing the supersets should result in the following:

[[2,3],[5]]

How can I accomplish this?


Solution

  • A set can only be a subset of another if it is smaller, thus by iterating over the sets in ascending order of size, we can check each element against the previously found minimal subsets to know if it is a minimal subset.

    def get_minimal_subsets(sets):
        sets = sorted(map(set, sets), key=len)
        minimal_subsets = []
        for s in sets:
            if not any(minimal_subset.issubset(s) for minimal_subset in minimal_subsets):
                minimal_subsets.append(s)
    
        return minimal_subsets
    
    l = [[1,2,3],[2,3],[2,4,3],[4,5],[5]]
    
    print(get_minimal_subsets(l))  # [{5}, {2, 3}]