python中有数学nCr函数吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4941753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a math nCr function in python?
提问by James Mertz
Possible Duplicates:
Statistics: combinations in Python
counting combinations and permutations efficiently
Project euler problem in python (problem 53)
I'm looking to see if built in with the math library in python is the nCr (n Choose r) function:
我想看看 python 中的数学库是否内置了 nCr (n Choose r) 函数:


I understand that this can be programmed but I thought that I'd check to see if it's already built in before I do.
我知道这可以编程,但我想在我做之前我会检查它是否已经内置。
采纳答案by dheerosaur
The following program calculates nCrin an efficient manner (compared to calculating factorials etc.)
以下程序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
As of Python 3.8, binomial coefficients are available in the standard library as math.comb:
从 Python 3.8 开始,二项式系数在标准库中可用math.comb:
>>> from math import comb
>>> comb(10,3)
120
回答by Mark Tolonen
Do you want iteration? itertools.combinations. Common usage:
你想要迭代吗?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']
If you just need to compute the formula, use math.factorial:
如果您只需要计算公式,请使用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)
In Python 3, use the integer division //instead of /to avoid overflows:
在 Python 3 中,使用整数除法//而不是/避免溢出:
return f(n) // f(r) // f(n-r)
return f(n) // f(r) // f(n-r)
Output
输出
6

