(python2.7)
組み合わせの総数
(引用: 組合せ (数学) - Wikipedia)
math.factorial を利用
import math def nCm(n, m): return math.factorial(n) / (math.factorial(m) * (math.factorial(n - m))) print nCm(43, 6) #-> 6096454
scipy.misc.comb を利用
pip install scipy
import scipy print scipy.misc.comb(43, 6) #-> 6096454.0
速度比較
In [67]: %timeit nCm(43, 6) 100000 loops, best of 3: 4.9 μs per loop In [68]: % timeit scipy.misc.comb(43, 6) 10000 loops, best of 3: 17 μs per loop
計算量が増えると scipy の方が圧倒的に速くなる
In [69]: %timeit nCm(43000, 6) 1 loops, best of 3: 1.25 s per loop In [70]: % timeit scipy.misc.comb(43000, 6) 100000 loops, best of 3: 18 μs per loop