我有一些代码用于计算排列和组合,现在我尝试让它可以处理更大的数字。
我已经找到了一个更好的排列算法,可以避免大量中间结果,但对于组合我仍然认为还有改进空间。
目前,我已经使用特殊情况来反映nCr的对称性,但我仍然希望找到一个更好的算法来避免调用factorial(r),因为这会产生一个不必要的大中间结果。如果没有此优化,最后一次测试需要花费很长时间才能计算出factorial(99000)。
是否有人可以建议更有效的方法来计算组合?
from math import factorial
def product(iterable):
prod = 1
for n in iterable:
prod *= n
return prod
def npr(n, r):
"""
Calculate the number of ordered permutations of r items taken from a
population of size n.
>>> npr(3, 2)
6
>>> npr(100, 20)
1303995018204712451095685346159820800000
"""
assert 0 <= r <= n
return product(range(n - r + 1, n + 1))
def ncr(n, r):
"""
Calculate the number of unordered combinations of r items taken from a
population of size n.
>>> ncr(3, 2)
3
>>> ncr(100, 20)
535983370403809682970
>>> ncr(100000, 1000) == ncr(100000, 99000)
True
"""
assert 0 <= r <= n
if r > n // 2:
r = n - r
return npr(n, r) // factorial(r)