Python permutation of permutation


Given permutation of index and dictionary of index, I want to get list of permutation for each index.

For example,

dict = { 1 : [A, B],
         2 : [C, D],
         3 : [E, F] }

perm = permutations([1, 2, 3])

# result: [ [A, B, C, D, E, F], [A, B, C, D, F, E], [A, B, D, C, E, F], [A, B, D, C, F, E], 
#           [B, A, C, D, E, F], [B, A, C, D, F, E], [B, A, D, C, E, F], [B, A, D, C, F, E] ]

How can I do this? I have no idea

Asked By: alryosha



For each permutation of keys, get the product of permutations of the associated lists:

from itertools import product, permutations

dct = {1: ["A", "B"], 2: ["C", "D"], 3: ["E", "F"]}

for perm in permutations(dct.keys()):
    for prod in product(*[list(permutations(dct[i])) for i in perm]):
        print([x for p in prod for x in p])

Output (some):

(1, 2, 3)
['A', 'B', 'C', 'D', 'E', 'F']
['B', 'A', 'D', 'C', 'F', 'E']
(1, 3, 2)
['A', 'B', 'E', 'F', 'C', 'D']
(3, 2, 1)
['E', 'F', 'C', 'D', 'A', 'B']
['F', 'E', 'D', 'C', 'B', 'A']
Answered By: tobias_k
import itertools

def add_reverse(val):
    val_temp = val.copy()
    return [val,val_temp]

def permutations(dictionary):
    lists = list(map(lambda i: add_reverse(i[1]), dictionary.items()))
    final_result = []
    for element in itertools.product(*lists):
        flat_list = list(itertools.chain.from_iterable(element))
    return final_result

res = permutations({ 1 : ['A', 'B'],
                     2 : ['C', 'D'],
                     3 : ['E', 'F'] }) 
Answered By: Eirini Kotzia

as a 1-liner:

from itertools import product, permutations, chain

d = {1 : ['A', 'B'], 2: ['C', 'D'], 3: ['E', 'F']}

def my_perm(L):
    return [list(chain(*x)) for x in product(*[permutations(d[i]) for i in L])]

perm = my_perm([1, 2, 3])
Answered By: Julien
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.