RosettaCodeData/Task/Evaluate-binomial-coefficients/Python/evaluate-binomial-coefficients-2.py

24 lines
569 B
Python
Raw Permalink Normal View History

2013-04-10 16:57:12 -07:00
from operator import mul
2019-09-12 10:33:56 -07:00
from functools import reduce
2013-04-10 16:57:12 -07:00
def comb(n,r):
''' calculate nCr - the binomial coefficient
>>> comb(3,2)
3
>>> comb(9,4)
126
>>> comb(9,6)
84
>>> comb(20,14)
38760
'''
2019-09-12 10:33:56 -07:00
if r > n-r:
# r = n-r for smaller intermediate values during computation
return ( reduce( mul, range((n - (n-r) + 1), n + 1), 1)
// reduce( mul, range(1, (n-r) + 1), 1) )
else:
return ( reduce( mul, range((n - r + 1), n + 1), 1)
// reduce( mul, range(1, r + 1), 1) )