web-dev-qa-db-ja.com

繰り返しのある順列の生成

私はitertoolsについて知っていますが、繰り返しなしで順列を生成できるだけです。

たとえば、2つのサイコロのすべての可能なサイコロロールを生成したいと思います。したがって、繰り返しを含む[1、2、3、4、5、6]のサイズ2のすべての順列が必要です:(1、1)、(1、2)、(2、1)...など

可能であれば、これをゼロから実装したくない

67
Bwmat

デカルト積 を探しています。

数学では、デカルト積(または積集合)は2つの集合の直接積です。

あなたの場合、これは{1, 2, 3, 4, 5, 6} バツ {1, 2, 3, 4, 5, 6}itertools が役立ちます:

import itertools
x = [1, 2, 3, 4, 5, 6]
[p for p in itertools.product(x, repeat=2)]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 1), (2, 2), (2, 3), 
 (2, 4), (2, 5), (2, 6), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5), (3, 6), 
 (4, 1), (4, 2), (4, 3), (4, 4), (4, 5), (4, 6), (5, 1), (5, 2), (5, 3), 
 (5, 4), (5, 5), (5, 6), (6, 1), (6, 2), (6, 3), (6, 4), (6, 5), (6, 6)]

完全に非効率的な方法で)ランダムなサイコロを振る:

import random
random.choice([p for p in itertools.product(x, repeat=2)])
(6, 3)
114
miku

順列を探しているのではなく、 デカルト積 が必要です。これには、itertoolsの product を使用します。

from itertools import product
for roll in product([1, 2, 3, 4, 5, 6], repeat = 2):
    print(roll)
26
Mark Byers

python 2.7および3.1には itertools.combinations_with_replacement 関数:

>>> list(itertools.combinations_with_replacement([1, 2, 3, 4, 5, 6], 2))
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 2), (2, 3), (2, 4), 
 (2, 5), (2, 6), (3, 3), (3, 4), (3, 5), (3, 6), (4, 4), (4, 5), (4, 6),
 (5, 5), (5, 6), (6, 6)]
6
SilentGhost

最初に、itertools.permutations(list)によって返されるジェネレーターを最初にリストに変換します。次に、set()を使用して、以下のような重複を削除できます。

def permutate(a_list):
    import itertools
    return set(list(itertools.permutations(a_list)))
0
Eric_HL_DoCode