Do you want iteration? itertools.combinations. Common usage:
>>> import itertools
>>> itertools.combinations['abcd',2]
>>> 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, math.factorial can be used, but is not fast for large
combinations, but see math.comb
below for an optimized calculation available in Python 3.8+:
import math
def nCr[n,r]:
f = math.factorial
return f[n] // f[r] // f[n-r]
if __name__ == '__main__':
print nCr[4,2]
Output:
6
As of Python 3.8, math.comb
can be used and is much faster:
>>> import math
>>> math.comb[4,2]
6