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
CodePudding user response:
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()):
print(perm)
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']
CodePudding user response:
import itertools
def add_reverse(val):
val_temp = val.copy()
val_temp.reverse()
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))
final_result.append(flat_list)
return final_result
res = permutations({ 1 : ['A', 'B'],
2 : ['C', 'D'],
3 : ['E', 'F'] })
print(res)
CodePudding user response:
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])