Statistics: combinations in Python

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

    A literal translation of the mathematical definition is quite adequate in a lot of cases (remembering that Python will automatically use big number arithmetic):

    from math import factorial
    
    def calculate_combinations(n, r):
        return factorial(n) // factorial(r) // factorial(n-r)
    

    For some inputs I tested (e.g. n=1000 r=500) this was more than 10 times faster than the one liner reduce suggested in another (currently highest voted) answer. On the other hand, it is out-performed by the snippit provided by @J.F. Sebastian.

提交回复
热议问题