Search code examples
pythonlistsubsetcriteria

Python find subsets of a list of lists that fulfil a specific condition


thanks for giving me the opportunity to ask a question here.

A small backstory: I need / want to find sets that fulfil certain conditions. These conditions can be quite complex, but I'll hopefully be able to adapt based on an easy example.

First, let's create an example:

from itertools import permutations
perm3 = list(permutations([1,2,3,4],3))

We create all permutations of length 3 from these numbers (e.g. (1,2,3),(1,3,2),...). Now, I would like to find all subsets that fulfil a specific condition. For example, find the subset of all permutations that have "3" never in the first place. That alone should be possible quite easily:

first_neq_3 = [tuple for tuple in perm3 if tuple[0]!= 3]

But, obviously that only gives me one subset - namely the "biggest" one. Now, I would like to find ALL subsets that fulfil this condition. A short example, let's say first_neq_3 = [(1,2,3),(2,1,3),(1,3,2),(2,3,1)] - then I would also like to find [(1,2,3),(2,1,3)] and so on.
I admit, it's a pretty simple problem for the example provided, but I am stuck and it gets more complicated with more complex conditions.


Solution

  • If I understand correctly, you need all the subsets of the list first_neq_3 above (of all possible lengths). Then you can get them using the code below

    from itertools import combinations
    sum(map(lambda r: list(combinations(first_neq_3, r)), range(1, len(first_neq_3)+1)), [])
    

    EXPLANATION

    The key here is the map function. The itertools.combinations gives you all the subsets of a list of a given length. Since we need the subsets of all lengths we perform that action using r as a dummy variable running over all possible lenghts. Since the first argument of the map must be a function is is handy to use a lambda expression.