In other words, it is a combination that takes out r out of n.
I want to write this in Python.
In such a case, use the higher-order function reduce
.
import operator as op
def ncr(n,r):
r = min(n-r,r)
if r == 0:
return 1
num_over = reduce(op.mul, xrange(n, n - r, -1))
num_under = reduce(op.mul, xrange(1,r + 1))
return num_over // num_under
If you write with a lambda expression,
reduce(lambda x, y: x * y, xrange(n, n - r, -1))
Write like.
Recommended Posts