Statistics: combinations in Python

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

    You can write 2 simple functions that actually turns out to be about 5-8 times faster than using scipy.special.comb. In fact, you don't need to import any extra packages, and the function is quite easily readable. The trick is to use memoization to store previously computed values, and using the definition of nCr

    # create a memoization dictionary
    memo = {}
    def factorial(n):
        """
        Calculate the factorial of an input using memoization
        :param n: int
        :rtype value: int
        """
        if n in [1,0]:
            return 1
        if n in memo:
            return memo[n]
        value = n*factorial(n-1)
        memo[n] = value
        return value
    
    def ncr(n, k):
        """
        Choose k elements from a set of n elements - n must be larger than or equal to k
        :param n: int
        :param k: int
        :rtype: int
        """
        return factorial(n)/(factorial(k)*factorial(n-k))
    

    If we compare times

    from scipy.special import comb
    %timeit comb(100,48)
    >>> 100000 loops, best of 3: 6.78 µs per loop
    
    %timeit ncr(100,48)
    >>> 1000000 loops, best of 3: 1.39 µs per loop
    

提交回复
热议问题