Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how do you generate permutations of an array where you only have one element from each column and row?

For example:

Say you have the following array:

[1,2,3]
[4,5,6]
[7,8,9]

and you want to generate this array:

[1,5,9]
[1,6,8]
[4,2,9]
[4,8,3]
[7,2,6]
[7,5,3]
like image 473
cmgerber Avatar asked Oct 28 '13 16:10

cmgerber


1 Answers

import itertools

A=[[1,2,3],
[4,5,6],
[7,8,9]]

for P in itertools.permutations(range(len(A))):
    print [A[p][i] for i,p in enumerate(P)]

Prints:

[1, 5, 9]
[1, 8, 6]
[4, 2, 9]
[4, 8, 3]
[7, 2, 6]
[7, 5, 3]
like image 136
Peter de Rivaz Avatar answered Oct 01 '22 16:10

Peter de Rivaz