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
Mark Tolonen Feb 09 2018-11-11T00: 00Z
source share