Is there a math nCr function in python?

Possible duplicates:
Statistics: Python Combinations
efficient counting of combinations and permutations
Pyler project euler problem (issue 53)

I am looking to embed the nCr (n Select r) function in the math library in python:

enter image description here

I understand that this can be programmed, but I thought that I would check if it is already built in before I do this.

+112
function python math
Feb 09 2018-11-11T00:
source share
2 answers

The following program calculates nCr efficient way (compared to calculating factorials, etc.)

 import operator as op from functools import reduce def ncr(n, r): r = min(r, nr) numer = reduce(op.mul, range(n, nr, -1), 1) denom = reduce(op.mul, range(1, r+1), 1) return numer / denom 
+118
Feb 09 '11 at 6:25
source share

Do you want iteration? itertools.combinations . General use:

 >>> 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 calculate the formula, use math.factorial :

 import math def nCr(n,r): f = math.factorial return f(n) / f(r) / f(nr) if __name__ == '__main__': print nCr(4,2) 

In Python 3, use integer division // instead of / to avoid overflow:

return f(n) // f(r) // f(nr)

Exit

 6 
+131
Feb 09 2018-11-11T00:
source share



All Articles