Is there a built-in nCr (n choose r) function included in the Python math
library like the one shown below?
I understand that the computation can be programmed, but I thought I'd check to see if it's built-in before I do.
Is there a built-in nCr (n choose r) function included in the Python math
library like the one shown below?
I understand that the computation can be programmed, but I thought I'd check to see if it's built-in before I do.
On Python 3.8+, use math.comb
:
>>> from math import comb
>>> comb(10, 3)
120
For older versions of Python, you can use the following program:
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
if r < 0: return 0
after reseting r to the min. –
Cumulous xrange
functions, but then reduce errors out because it does not know the initial value (and even then, the value should be 1 for multiplication, which won't give you the correct answer of 0). –
Cumulous ncr(n, r)
is equal to ncr(n, n-r)
–
Baleful n = 100
and k = 18
and it returned 3.066451080298821e+19
(also written as 30664510802988208128
) whereas the correct answer is 30664510802988208300
. You can correct this with numer // denom
instead of numer / denom
. It will return the result as an integer division instead of a floating point one. I think this behaviour is caused by the lack of precision of a float number. –
Colored scipy.special.comb
for older python versions –
Pease Do you want iteration? Use itertools.combinations
. Common usage:
>>> import itertools
>>> itertools.combinations('abcd', 2)
<itertools.combinations object at 0x104e9f010>
>>> 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)
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
math.factorial
returns a float, and not an arbitrary-precision integer, maybe? –
Pascia 10000 C 500
and returns an answer of 861 digits. Accurate and not particularly "slow" :^) –
Comp scipy.special.comb
for older python versions –
Pease © 2022 - 2024 — McMap. All rights reserved.
import scipy.misc
thenscipy.misc.comb(N,k)
– Projectile