from operator import mul # or mul=lambda x,y:x*y
from fractions import Fraction
def nCk(n,k):
return int( reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1) )
PS.已编辑以替换int(round(reduce(mul, (float(n-i)/(i+1) for i in range(k)), 1)))
与int(reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1))一起使用,因此对于大N/K不会出错
def choose(n, k):
"""
A fast way to calculate binomial coefficients by Andrew Dalke (contrib).
"""
if 0 <= k <= n:
ntok = 1
ktok = 1
for t in xrange(1, min(k, n - k) + 1):
ntok *= n
ktok *= t
n -= 1
return ntok // ktok
else:
return 0
def comb(N,k): # from scipy.comb(), but MODIFIED!
if (k > N) or (N < 0) or (k < 0):
return 0L
N,k = map(long,(N,k))
top = N
val = 1L
while (top > (N-k)):
val *= top
top -= 1
n = 1L
while (n < k+1L):
val /= n
n += 1
return val
为什么不自己写呢?这是一个单列或类似的:
测试-打印帕斯卡三角形:
PS.已编辑以替换
int(round(reduce(mul, (float(n-i)/(i+1) for i in range(k)), 1)))
与int(reduce(mul, (Fraction(n-i, i+1) for i in range(k)), 1))
一起使用,因此对于大N/K不会出错快速搜索google代码(它使用来自@Mark Byers's answer的公式):
choose()
比scipy.misc.comb()
快10倍(在所有0<;=(n,k)<;1e3对上测试),如果你需要一个精确的答案的话。请参见scipy.special.comb(旧版本scipy中的scipy.misc.comb)。当
exact
为False时,它使用gammaln函数在不占用大量时间的情况下获得良好的精度。在确切的情况下,它返回一个任意精度的整数,这可能需要很长时间来计算。相关问题 更多 >
编程相关推荐