Fix Python – Is there a math nCr function in python? [duplicate]

Question

Asked By – James Mertz

I’m looking to see if built in with the math library in python is the nCr (n Choose r) function:

enter image description here

I understand that this can be programmed but I thought that I’d check to see if it’s already built in before I do.

Now we will see solution for issue: Is there a math nCr function in python? [duplicate]


Answer

The following program calculates nCr in an efficient manner (compared to calculating factorials etc.)

import operator as op
from functools import reduce

def ncr(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom  # or / in Python 2

As of Python 3.8, binomial coefficients are available in the standard library as math.comb:

>>> from math import comb
>>> comb(10,3)
120

This question is answered By – dheerosaur

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0