LoginSignup
28
21

More than 5 years have passed since last update.

Pythonで順列と組み合わせ

Last updated at Posted at 2015-12-26

Pythonでは、順列、組み合わせとかを本当に直感的に表示・計算出来て便利。

参考

  • ここの内容で全て事足りました。

順列 (P:Permutations)

a,b,c,d,e 5つの要素が会った時の並べ方のパターンは、5!(5の階乗個)。つまり、

_5 P _5 = 5! = 5 * 4 * 3 * 2 * 1 = 120

これをPythonで求めるためには、

#coding:utf-8
import itertools

#並べる対象
s = ['a','b','c','d','e']

#list化
p = list(itertools.permutations(s));

#パターン表示
#print p

#パターン数表示
print len(p)

とする。
5つの中から、3つを選んで並べる場合、

_5 P _3 = 5 * 4 * 3 = 60

となる。これをPythonで求める場合、

p = list(itertools.permutations(s,3));

とする(上記、抜粋)。

組み合わせ (C:Combinations)

次に順列。並べ順を問わず、要素が同じなら1つと数える。例えば、(a,b,c)と(a,c,b)等は1つと考える。
上記と同様、a,b,c,d,eから3つを選らんだ場合の組み合わせは、

_5 C _3 = \frac{_5 P _3}{3!} = \frac{5 * 4 * 3}{3 * 2 * 1} =  10

となる。 これをPythonで計算するには、

#coding:utf-8
import itertools

#並べる対象
s = ['a','b','c','d','e']

#list化
c = list(itertools.combinations(s,3));

#パターン表示
#print c

#パターン数表示
print len(c)

とする。

28
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
21