可能的重复项:
Statistics: combinations in Python
counting combinations and permutations efficiently
Project euler problem in python (problem 53)
我想看看python中的数学库是不是内置了nCr (n Choose r)函数:
我知道这是可以编程的,但我想我应该先检查一下它是否已经内置。
发布于 2011-02-09 14:25:28
下面的程序以高效的方式计算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
从Python3.8开始,二项式系数在标准库中以math.comb
的形式提供
>>> from math import comb
>>> comb(10,3)
120
发布于 2011-02-09 14:09:46
是否要迭代?itertools.combinations。常见用法:
>>> import itertools
>>> itertools.combinations('abcd',2)
<itertools.combinations object at 0x01348F30>
>>> 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']
如果您只需要计算公式,请使用math.factorial
import math
def nCr(n,r):
f = math.factorial
return f(n) / f(r) / f(n-r)
if __name__ == '__main__':
print nCr(4,2)
在Python3中,使用整数除法//
而不是/
来避免溢出:
return f(n) // f(r) // f(n-r)
输出
6
https://stackoverflow.com/questions/4941753
复制相似问题