Skip to content

Instantly share code, notes, and snippets.

@DiogoRibeiro7
Forked from rougier/binomial.py
Created April 11, 2019 23:30
Show Gist options
  • Save DiogoRibeiro7/cce979c0ba94c22f14d78b8b1798251d to your computer and use it in GitHub Desktop.
Save DiogoRibeiro7/cce979c0ba94c22f14d78b8b1798251d to your computer and use it in GitHub Desktop.
A fast way to calculate binomial coefficients in python (Andrew Dalke)
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment