Statistics: combinations in Python

前端 未结 18 1545
南旧
南旧 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条回答
  •  Happy的楠姐
    2020-11-27 10:49

    If your program has an upper bound to n (say n <= N) and needs to repeatedly compute nCr (preferably for >>N times), using lru_cache can give you a huge performance boost:

    from functools import lru_cache
    
    @lru_cache(maxsize=None)
    def nCr(n, r):
        return 1 if r == 0 or r == n else nCr(n - 1, r - 1) + nCr(n - 1, r)
    

    Constructing the cache (which is done implicitly) takes up to O(N^2) time. Any subsequent calls to nCr will return in O(1).

提交回复
热议问题