【統計学】順列と組み合わせ(RとPython)
高校数学Aでおなじみの場合の数。下記教科書では5章に簡単に説明されています。
Rで実装
#階乗 #5! factorial(5) #[1] 120 #順列 #8個から3つ並べる方法 n <- 8 r <- 3 prod((n-r+1):n) #[1] 336 #3つのものを並べる方法一覧 #install.packages("e1071") library(e1071) permutations(3) #[,1] [,2] [,3] #[1,] 1 2 3 #[2,] 2 1 3 #[3,] 2 3 1 #[4,] 1 3 2 #[5,] 3 1 2 #[6,] 3 2 1
Pythonで実装
import itertools import math #階乗 print(math.factorial(5)) #120 #順列 ##5つのものから3つを並べる方法 df = ('a', 'b', 'c', 'd', 'e') p = [] #すべての順列が入る for i in itertools.permutations(df,3): p.append(i) len(p) #順列の個数が入る #Out[27]: 60 #組み合わせ ##5つのものから3つを選ぶ方法 df = ('a', 'b', 'c', 'd', 'e') c = [] #すべての組み合わせが入る for i in itertools.combinations(df,3): c.append(i) len(c) #組み合わせの個数が入る #Out[28]: 10