python中有数学nCr函数吗?

时间:2011-02-09 05:51:13

标签: python function math

  

可能重复:
  Statistics: combinations in Python
  counting combinations and permutations efficiently
  Project euler problem in python (problem 53)

我想看看在python中使用数学库内置的是nCr(n选择r)函数:

enter image description here

据我所知,这可以编程,但我想我会先查看它是否已经内置。

2 个答案:

答案 0 :(得分:150)

你想要迭代吗? 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)

在Python 3中,使用整数除法//而不是/来避免溢出:

return f(n) // f(r) // f(n-r)

输出

6

答案 1 :(得分:141)

以下程序以有效的方式计算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