开发者

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

This question already has answers here: Statistics: combinations in Python (19 answers) 开发者_StackOverflow counting combinations and permutations efficiently (13 answers) Closed 8 months ago.

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

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

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.


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


Do you want iteration? itertools.combinations. Common usage:

>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']

If you just need to compute the formula, math.factorial can be used, but is not fast for large combinations, but see math.comb below for an optimized calculation available in Python 3.8+:

import math

def nCr(n,r):
    f = math.factorial
    return f(n) // f(r) // f(n-r)

if __name__ == '__main__':
    print nCr(4,2)

Output:

6

As of Python 3.8, math.comb can be used and is much faster:

>>> import math
>>> math.comb(4,2)
6
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜