Is there a math nCr function in python?

James Mertz picture James Mertz · Feb 9, 2011 · Viewed 279.8k times · Source

Possible Duplicates:
Statistics: combinations in Python
counting combinations and permutations efficiently
Project euler problem in python (problem 53)

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.

Answer

dheerosaur picture dheerosaur · Feb 9, 2011

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