2017-06-20 26 views
0

ある長さのすべての可能な順列を1つまたは両方の整数を使って2つの整数で計算する簡単な方法はありますか?たとえば、私の整数が1と2で、長さ3のすべての可能な順列を計算したい場合は、(111,112,121,122,211,212,221,222)を取得する必要があります。私はitertools.permutationsは動作すると思ったが、長さが>整数の場合、明らかに項目は返されない。与えられた長さの2つの整数のPythonパーミュテーション

+0

おかげで、それは私がまさに必要です。私はなぜそれが私の調査で上がらなかったのか分からない。 – henrypj

答えて

-1
import itertools 

length = 3 
possible_int = [1,2] 
all_permutations = [] 
for i in range(length+1): 
    first = [possible_int[0]]*i 
    second = [possible_int[1]]*(length-i) 
    permutations = [list(x) for x in itertools.permutations(first+second)] 
    for element in permutations: 
     if element not in all_permutations: 
      all_permutations.append(element) 

print(all_permutations) 
1

あなたが探していることは、単にある場合:

[(1, 1), (1, 2), (2, 1), (2, 2)] 

が、その後Permutation of x length of 2 charactersを見て、このスレッドが重複しています。

の場合は、代わりに、あなたが探していることは

[11, 12, 21, 22] 

が、その後使用されています

import itertools as it 
print([int(str(i) + str(j)) for i, j in it.product(l, repeat=2)]) 
[11, 12, 21, 22] 
関連する問題