Mathematically speaking, the binomial coefficient is the number of combinations of
r number of items that could be used to form a set of
n items, or we could say that this coefficient is the number of ways of selecting outcomes in an unordered way from possibilities.
In this article, we will calculate the binomial coefficient in Python.
scipy Module to Calculate the Binomial Coefficient in Python
SciPy has two methods to calculate the binomial coefficients. The first function is called
scipy.special.binom(). This function generally handles large values efficiently.
import scipy.special print(scipy.special.binom(10,5))
The second function that returns the binomial coefficient is called
import scipy.special print(scipy.special.comb(10,5))
math.comb() Function to Calculate the Binomial Coefficient in Python
comb() function from the
math module returns the combination of the given values, which essentially has the same formula as the binomial coefficient. This method is an addition to recent versions of Python 3.8 and above.
import math print(math.comb(10,5))
operator Module to Calculate the Binomial Coefficient in Python
In older versions of Python,
math.factorial is not present and thus, could not be used. To compensate for this and generate the output in much less time, we can use the
operator modules together.
A lambda function product is created with
operator.mul to get the product of numbers.
import math import operator from functools import reduce product = lambda m,n: reduce(operator.mul, range(m, n+1), 1) x = 10 y = 5 product(y+1, x) / product(1, x-y)
math.fact() Function to Calculate the Binomial Coefficient in Python
We can use the
fact() function from the
math module to implement the mathematical formula for calculating the binomial coefficient.
See the code below.
from math import factorial as fact def binomial(n, r): return fac(n) // fac(r) // fac(n - r) print(binomial(10,5))