Statistics: combinations in Python

前端 未结 18 1515
南旧
南旧 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条回答
  •  -上瘾入骨i
    2020-11-27 10:43

    Using dynamic programming, the time complexity is Θ(n*m) and space complexity Θ(m):

    def binomial(n, k):
    """ (int, int) -> int
    
             | c(n-1, k-1) + c(n-1, k), if 0 < k < n
    c(n,k) = | 1                      , if n = k
             | 1                      , if k = 0
    
    Precondition: n > k
    
    >>> binomial(9, 2)
    36
    """
    
    c = [0] * (n + 1)
    c[0] = 1
    for i in range(1, n + 1):
        c[i] = 1
        j = i - 1
        while j > 0:
            c[j] += c[j - 1]
            j -= 1
    
    return c[k]
    

提交回复
热议问题