2016-10-09 4 views
3

サイズKの0-1行列の可能なすべての組み合わせをNで生成するにはどうすればよいですか?Pythonで0-1のすべての可能な組み合わせを生成する方法は?

たとえば、K = 2、N = 2とすると、次の組み合わせが得られます。

combination 1 
[0, 0; 
0, 0]; 
combination 2 
[1, 0; 
0, 0]; 
combination 3 
[0, 1; 
0, 0]; 
combination 4 
[0, 0; 
1, 0]; 
combination 5 
[0, 0; 
0, 1]; 
combination 6 
[1, 1; 
0, 0]; 
combination 7 
[1, 0; 
1, 0]; 
combination 8 
[1, 0; 
0, 1]; 
combination 9 
[0, 1; 
1, 0]; 
combination 10 
[0, 1; 
0, 1]; 
combination 11 
[0, 0; 
1, 1]; 
combination 12 
[1, 1; 
1, 0]; 
combination 13 
[0, 1; 
1, 1]; 
combination 14 
[1, 0; 
1, 1]; 
combination 15 
[1, 1; 
0, 1]; 
combination 16 
[1, 1; 
1, 1]; 
+0

さらにアルゴリズムの質問に似ています - > http://programmers.stackexchange.com/ – tomasyany

答えて

5

numpyitertoolsとワンライナー溶液:

[np.reshape(np.array(i), (K, N)) for i in itertools.product([0, 1], repeat = K*N)] 

説明:product関数は入力のデカルト積を返します。たとえば、product([0, 1], [0, 1])は、すべての可能な置換を含む反復子を返します。[0, 1][0, 1]です。換言すれば、製品イテレータから描画:

for i, j in product([0, 1], [0, 1]): 

は、forループネストされた2を実行する実際等しい:

for i in [0, 1]: 
    for j in [0, 1]: 

ザforループ既に特定の場合のために手で問題を解決する上記K, N = (1, 0)です。上記の考え方を続けて、ベクトルiのすべての可能な0/1状態を生成するには、深さがlのネストされたfor-loopに相当するイテレータからサンプルを描画する必要があります。ここではl = len(i)です。幸いなことに、itertoolsは、repeatキーワード引数でこれを行うためのフレームワークを提供します。 OPの問題の場合、この置換の深さはK*Nである必要があります。リストの理解の各段階で適切なサイズの小さな配列に再構成できます。

関連する問題