python中有数学nCr函数吗?

2024-05-15 23:12:29 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicates:
Statistics: combinations in Python
counting combinations and permutations efficiently
Project euler problem in python (problem 53)

我想看看python中的数学库是否内置了nCr(n Choose r)函数:

enter image description here

我知道这是可以编程的,但我想我会先检查一下它是否已经内置了。


Tags: andinproject数学内置duplicatesstatisticsproblem
2条回答

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

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

相关问题 更多 >