Statistics: combinations in Python

前端 未结 18 1581
南旧
南旧 2020-11-27 10:14

I need to compute combinatorials (nCr) in Python but cannot find the function to do that in math, numpy or stat libraries. Something

18条回答
  •  臣服心动
    2020-11-27 10:43

    The direct formula produces big integers when n is bigger than 20.

    So, yet another response:

    from math import factorial
    
    reduce(long.__mul__, range(n-r+1, n+1), 1L) // factorial(r)
    

    short, accurate and efficient because this avoids python big integers by sticking with longs.

    It is more accurate and faster when comparing to scipy.special.comb:

     >>> from scipy.special import comb
     >>> nCr = lambda n,r: reduce(long.__mul__, range(n-r+1, n+1), 1L) // factorial(r)
     >>> comb(128,20)
     1.1965669823265365e+23
     >>> nCr(128,20)
     119656698232656998274400L  # accurate, no loss
     >>> from timeit import timeit
     >>> timeit(lambda: comb(n,r))
     8.231969118118286
     >>> timeit(lambda: nCr(128, 20))
     3.885951042175293
    

提交回复
热议问题