# Python - How To Binomial Coefficient in Python

ID : 357

viewed : 65

Tags : PythonPython Math

96

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.

## Use the `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.

For example,

``import scipy.special print(scipy.special.binom(10,5)) ``

Output:

``252.0 ``

The second function that returns the binomial coefficient is called `scipy.special.comb()`.

For example,

``import scipy.special print(scipy.special.comb(10,5)) ``

Output:

``252.0 ``

## Use the `math.comb()` Function to Calculate the Binomial Coefficient in Python

The `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.

For example,

``import math print(math.comb(10,5)) ``

Output:

``252 ``

## Use the `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 `math` and `operator` modules together.

A lambda function product is created with `operator.mul` to get the product of numbers.

For example,

``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) ``

Output:

``252 ``

## Use the `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)) ``

Output:

``252 ``