Statistics: combinations in Python

前端 未结 18 1598
南旧
南旧 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

    This is @killerT2333 code using the builtin memoization decorator.

    from functools import lru_cache
    
    @lru_cache()
    def factorial(n):
        """
        Calculate the factorial of an input using memoization
        :param n: int
        :rtype value: int
        """
        return 1 if n in (1, 0) else n * factorial(n-1)
    
    @lru_cache()
    def ncr(n, k):
        """
        Choose k elements from a set of n elements,
        n must be greater than or equal to k.
        :param n: int
        :param k: int
        :rtype: int
        """
        return factorial(n) / (factorial(k) * factorial(n - k))
    
    print(ncr(6, 3))
    

提交回复
热议问题