2018年1月5日金曜日

[Python] 順列,組合せ

順列,組合せの計算例を以下に示します.
計算例は,REPLで実行しています.

順列
1, 2, 3 の3つのすべての並べ方は, $3! = 3 \times 2 \times 1 = 6$ 通りとなります.
順列を求める時には,itertoolsのpermutationsを利用します.
>>> import itertools
>>> seq = (1, 2, 3)
>>> list(itertools.permutations(seq))
[(1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]
>>> len(list(itertools.permutations(seq)))
6
6通りの組み合わせであることが確認できます.

1, 2, 3, 4, 5 から3つを選ぶ並べ方は,${}_5 P _3=5 \times 4 \times 3 = 60$ 通りとなります.
順列の際には,permutations の第二引数として,選ぶ数(この例では3)を記載します.
>>> seq2 = (1, 2, 3, 4, 5)
>>> list(itertools.permutations(seq2, 3))
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 2), (1, 3, 4), (1, 3, 5), (1, 4, 2), (1, 4, 3), (1, 4, 5), (1, 5, 2), (1, 5, 3), (1, 5, 4), (2, 1, 3), (2, 1, 4), (2, 1, 5), (2, 3, 1), (2, 3, 4), (2, 3, 5), (2, 4, 1), (2, 4, 3), (2, 4, 5), (2, 5, 1), (2, 5, 3), (2, 5, 4), (3, 1, 2), (3, 1, 4), (3, 1, 5), (3, 2, 1), (3, 2, 4), (3, 2, 5), (3, 4, 1), (3, 4, 2), (3, 4, 5), (3, 5, 1), (3, 5, 2), (3, 5, 4), (4, 1, 2), (4, 1, 3), (4, 1, 5), (4, 2, 1), (4, 2, 3), (4, 2, 5), (4, 3, 1), (4, 3, 2), (4, 3, 5), (4, 5, 1), (4, 5, 2), (4, 5, 3), (5, 1, 2), (5, 1, 3), (5, 1, 4), (5, 2, 1), (5, 2, 3), (5, 2, 4), (5, 3, 1), (5, 3, 2), (5, 3, 4), (5, 4, 1), (5, 4, 2), (5, 4, 3)]
>>> 
>>> len(list(itertools.permutations(seq2, 3)))
60
60通りの組み合わせであることが確認できます.

組合せ
1, 2, 3, 4, 5 から3つを選ぶ組合せは, ${}_5 C _3= \frac{{}_5 P_3}{3!} = 10$ 通りとなります.
順列を求める時には,itertoolsのccombinationsを利用します.
>>> list(itertools.combinations(seq2, 3))
[(1, 2, 3), (1, 2, 4), (1, 2, 5), (1, 3, 4), (1, 3, 5), (1, 4, 5), (2, 3, 4), (2, 3, 5), (2, 4, 5), (3, 4, 5)]
>>> len(list(itertools.combinations(seq2, 3)))
10
10通りの組合せであることが確認できます.

上記の例のJupyter NotebookはGitHubFactorialPermutationCombination.ipynbで見ることができます.

0 件のコメント :

コメントを投稿