Search code examples
pythoncombinationspermutationpython-itertools

How to generate all the possible permutations based on a quota?


Given two lists X and Y:

X = ['A', 'B', 'C', 'D']

Y = ['I', 'J', 'K', 'L', 'M', 'N']

How to create all the possible sets of 4 combinations with the restriction of considering at least 2 elements of X and Y. For example, a valid combination would look like this:

[('A', 'J', 'M', 'D'), ..., ('I', 'M', 'B', 'C')]

The reason is that it contains 2 elements from X and Y. The combination [('A', 'B', 'M', 'D')] is not valid because it containes 3 elements from X and 1 from Y. So far I tried to:

import itertools
set(list(itertools.permutations([e for e in zip(X, Y)])))

However, this violates the quota restriction. What is the correct way of implementing the quota permutation?


Solution

  • You just need to do permutations of 2 from each list and combine them, then do all the combinations of each set of 4:

    from itertools import permutations, combinations
    X = ['A', 'B', 'C', 'D']
    Y = ['I', 'J', 'K', 'L', 'M', 'N']
    
    x = (n+m for n in permutations(X,2) for m in permutations(Y,2))
    for i in x:
        print(list(combinations(i,4)))