Skip to content

Instantly share code, notes, and snippets.

@Radcliffe
Created June 1, 2019 21:16
Show Gist options
  • Save Radcliffe/fe35d4524277fde9ac2e518612064ea4 to your computer and use it in GitHub Desktop.
Save Radcliffe/fe35d4524277fde9ac2e518612064ea4 to your computer and use it in GitHub Desktop.
Binomial coefficient in Python
# Python script to calculate the binomial coefficient C(n, k)
# where n is an integer or floating point number and k is an integer.
#
# We use the following general definition:
# C(n, k) = n(n-1)(n-2)...(n-k+1) / k! if k >= 0,
# 0 if k < 0.
#
# For n < 0, we use the negative binomial identity
# C(n, k) = (-1)^k * C(k - n - 1, k)
#
# We also use the symmetric identity
# C(n, k) = C(n, n - k)
# when n > 0 and n/2 < k < n.
#
# Reference: "Concrete Mathematics" by Ronald Graham, Donald Knuth, and Oren Patashnik.
def binomial_coefficient(n, k):
if not isinstance(k, int):
raise ValueError('The second argument must be an integer.')
if k < 0:
return 0
if n < 0:
return (-1) ** k * binomial_coefficient(k - n - 1, k)
if k > n:
return 0
if k > n // 2:
k = n - k
result = 1
for i in range(k):
result = result * (n - i) // (i + 1)
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment