Statistics: combinations in Python

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

    That's probably as fast as you can do it in pure python for reasonably large inputs:

    def choose(n, k):
        if k == n: return 1
        if k > n: return 0
        d, q = max(k, n-k), min(k, n-k)
        num =  1
        for n in xrange(d+1, n+1): num *= n
        denom = 1
        for d in xrange(1, q+1): denom *= d
        return num / denom
    

提交回复
热议问题