Statistics: combinations in Python

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

    Here is an efficient algorithm for you

    for i = 1.....r
    
       p = p * ( n - i ) / i
    
    print(p)
    

    For example nCr(30,7) = fact(30) / ( fact(7) * fact(23)) = ( 30 * 29 * 28 * 27 * 26 * 25 * 24 ) / (1 * 2 * 3 * 4 * 5 * 6 * 7)

    So just run the loop from 1 to r can get the result.

提交回复
热议问题