Get list of combinations for K groups of N members and L groups of M members

Viewed 1080

In Python; what is the best way to get a list of combinations for k groups of n members and l groups of m members given a list of possible members g?

Example, given a list of elements:

g = ["A", "B", "C", "D", "E", "F", "G"]

What I want is to have a list li of all combinations for e.g. 2(=k) groups of 2(=n) and 1(=l) group of 3(=m):

[["AB", "CD", "EFG"],
 ["AC", "BD", "EFG"],
 ["AD", "CB", "EFG"],
 ["AE", "CD", "BFG"],
 ["AF", "CD", "BEG"],... ]
  1. I don't want any repetition of elements accross any of the groups (equivalent of saying: I want every different element to appear once accross all the groups for every different combination).

    E.g. ["AB", "AD", "EFG"] is not a valid combination as it has the element A more than once accross all groups.

  2. I don't want different permutations inside a group;

    E.g. ["AB", "CD", "EFG"] should not be repeated in a form like ["BA", "DC", "EGF"].

  3. Also, if a combination appears in any of the k-groups I don't want that same combination in the k-groups if the l-groups are just the same (and same for l-groups).

    E.g. if["AB", "CD", "EFG"] appears, [ "CD", "AB", "EFG"] should not appear again.

To be clear, I'm only interested in the case where the groups will always fit neatly/exactly in the total group of elements to be used(g):

E.g. 2x2 + 1x3 == 7 == len(["A", "B", "C", "D", "E", "F", "G"]), 1x2 + 1x3 == 5 == len(["A", "B", "C", "D", "E"]).


I could use Python's permutations function and just group together in k groups of n and l groups of m in each permutation, but I will have a lot of unnecessary iterations for more elements.

3 Answers
Related