if n is not far from r, then using the recursive definition of the combination is probably better, since xC0 == 1 you will only have a few iterations:
The relevant recursive definition is here:
nCr = (n-1) C (r-1) * n / r
This can be easily calculated using tail recursion with the following list:
(n - r, 1), (n - r + 2, 2), ..., (n - 1, r - 1), (n, r)]
which, of course, is easily generated in Python (we omit the first entry, since nC0 = 1) by izip(xrange(n - r + 1, n+1), xrange(1, r+1)) Note that this assumes r <= n you need to check this and replace them if they are not. Also to optimize use, if r <n / 2, then r = n - r.
Now we just need to apply the recursion step using tail recursion with reduction. We start with 1, since nC0 is 1, and then multiply the current value by the next entry from the list, as shown below.
from itertools import izip reduce(lambda x, y: x * y[0] / y[1], izip(xrange(n - r + 1, n+1), xrange(1, r+1)), 1)
wich Jan 19 '10 at 20:11 2010-01-19 20:11
source share