Search code examples
pythonfilterpermutationpython-itertools

How to find all permutations in a list of sets except permutations from own set?


Note: I'm using Python 3.

I have a list of sets of varying length, e.g.:

list_1 = [{(3, 4), (3, 1), (3, 3), (3, 2), (3, 5)}, {(9, 10), (9, 7), (9, 8), (9, 9)}, {(2, 9), (3, 9), (1, 9)}, {(6, 2), (5, 2)}, {(8, 3)}]

I want to find each tuple pair permutation, except where the pair is of two tuples in the same set. For example, (3,4)(9,10) and (3,1)(9,10) would be acceptable, but I do not want to output the pairs (3,4)(3,1) or (6,2)(5,2). How do I achieve this?

For some background, each set represents contiguous coordinates on a 10*10 grid. I want to find if any cell in one set is near any cell in another set, but I do not want cells in one set to check if they are near cells in their own set.

I tried to implement the following:


list_2 = itertools.permutations(list_1,2)

but this gives ALL permutations (as expected). Can I somehow implement the filter() function or something similar?


Solution

  • You can first permute the sets and then apply itertools.product to get the pairs from the sets.

    from itertools import permutations, product
    
    list_1 = [{(3, 4), (3, 1), (3, 3), (3, 2), (3, 5)}, {(9, 10), (9, 7), (9, 8), (9, 9)}, {(2, 9), (3, 9), (1, 9)}, {(6, 2), (5, 2)}, {(8, 3)}]
    
    pairs = [pair for ss in permutations(list_1, r=2) for pair in product(*ss)]
    
    print(pairs) # [((3, 3), (9, 10)), ((3, 3), (9, 7)), ((3, 3), (9, 8)), ...