The nPr (permutation) formula is: nPr = n!/(n-r)! The nCr (combination) formula is: nCr = n!/r!(
Solution. In both of our solving processes, we see that 5 C 2 = 10. In other words, there are 10 possible combinations of 2 objects chosen from 5 objects.
The ** operator in Python is used to raise the number on the left to the power of the exponent of the right. That is, in the expression 5 ** 3 , 5 is being raised to the 3rd power. In mathematics, we often see this expression rendered as 5³, and what is really going on is 5 is being multiplied by itself 3 times.
The following program calculates nCr
in an efficient manner (compared to calculating factorials etc.)
import operator as op
from functools import reduce
def ncr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom # or / in Python 2
As of Python 3.8, binomial coefficients are available in the standard library as math.comb
:
>>> from math import comb
>>> comb(10,3)
120
Do you want iteration? itertools.combinations. Common usage:
>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> list(itertools.combinations('abcd',2))
[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'c'), ('b', 'd'), ('c', 'd')]
>>> [''.join(x) for x in itertools.combinations('abcd',2)]
['ab', 'ac', 'ad', 'bc', 'bd', 'cd']
If you just need to compute the formula, use math.factorial:
import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
if __name__ == '__main__':
print nCr(4,2)
In Python 3, use the integer division //
instead of /
to avoid overflows:
return f(n) // f(r) // f(n-r)
6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With