Possible Duplicates:
Statistics: combinations in Python
counting combinations and permutations efficiently
Project euler problem in python (problem 53)
我想看看python中内置的数学库是否是nCr(n Choose r)函数:
我知道这是可以编程的,但我想我应该先判断一下它是否已经内置了.
Possible Duplicates:
Statistics: combinations in Python
counting combinations and permutations efficiently
Project euler problem in python (problem 53)
我想看看python中内置的数学库是否是nCr(n Choose r)函数:
我知道这是可以编程的,但我想我应该先判断一下它是否已经内置了.
以下程序以高效的方式计算nCr
(与计算阶乘等相比)
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
从Python 3.8开始,标准库中的二项式系数为math.comb
:
>>> from math import comb
>>> comb(10,3)
120