Created
January 25, 2016 09:50
-
-
Save rougier/ebe734dcc6f4ff450abf to your computer and use it in GitHub Desktop.
A fast way to calculate binomial coefficients in python (Andrew Dalke)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def binomial(n, k): | |
""" | |
A fast way to calculate binomial coefficients by Andrew Dalke. | |
See http://stackoverflow.com/questions/3025162/statistics-combinations-in-python | |
""" | |
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 |
Formatted:
def binomial(n, k):
if not 0 <= k <= n:
return 0
b = 1
for t in range(min(k, n-k)):
b *= n
b /= t+1
n -= 1
return int(b)
So for example when you call binomial(5, 2)
it returns 10
.
You can use b //= t+1
to avoid final cast.
The intention was that this should use only integer arithmetic (my version was converted from C code which used /=). So yes, this is better:
def binomial(n, k):
if not 0 <= k <= n:
return 0
b = 1
for t in range(min(k, n-k)):
b *= n
b //= t+1
n -= 1
return b
def C(n, k): if k == 0 or k == n: return 1 else: return C(n-1, k) + C(n-1, k-1)
It is much more efficient NOT to use recursion.
Try this....a short way by importing comb
from math
library
from math import comb
def coefficient(n,r):
return comb(n,r)
print(coefficient(5,2))
Change coefficient values to your desire
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
def binom(n,k): # better version - we don't need two products!
if not 0<=k<=n: return 0
b=1
for t in range(min(k,n-k)):
b*=n; b/=t+1; n-=1
return b