Statistics: combinations in Python

前端 未结 18 1591
南旧
南旧 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:36

    Here's another alternative. This one was originally written in C++, so it can be backported to C++ for a finite-precision integer (e.g. __int64). The advantage is (1) it involves only integer operations, and (2) it avoids bloating the integer value by doing successive pairs of multiplication and division. I've tested the result with Nas Banov's Pascal triangle, it gets the correct answer:

    def choose(n,r):
      """Computes n! / (r! (n-r)!) exactly. Returns a python long int."""
      assert n >= 0
      assert 0 <= r <= n
    
      c = 1L
      denom = 1
      for (num,denom) in zip(xrange(n,n-r,-1), xrange(1,r+1,1)):
        c = (c * num) // denom
      return c
    

    Rationale: To minimize the # of multiplications and divisions, we rewrite the expression as

        n!      n(n-1)...(n-r+1)
    --------- = ----------------
     r!(n-r)!          r!
    

    To avoid multiplication overflow as much as possible, we will evaluate in the following STRICT order, from left to right:

    n / 1 * (n-1) / 2 * (n-2) / 3 * ... * (n-r+1) / r
    

    We can show that integer arithmatic operated in this order is exact (i.e. no roundoff error).

提交回复
热议问题