Method 1 is faster 10 times than method 2
Method 1:
- Download package "gmpy2" from https://code.google.com/p/gmpy/
- Install with the corresponding Python (e.g, 2.7, 3.1,...)
import gmpy2
a = gmpy2.comb (5, 3)
--> The result is 10
Method 2
def choose(n, k):
"""
A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
"""
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in xrange(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0
Method 3:
- Using
scipy.misc.comb()