【问题标题】:Is there a math nCr function in python? [duplicate]python中有数学nCr函数吗? [复制]
【发布时间】:2011-06-23 22:15:48
【问题描述】:

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

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

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

【问题讨论】:

标签: python function math


【解决方案1】:

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

从 Python 3.8 开始,二项式系数在标准库中以 math.comb 的形式提供:

>>> from math import comb
>>> comb(10,3)
120

【讨论】:

  • 为什么理解不只是 xrange?
  • 可以使用阶乘计算分母,这在 Python 2 中是相当的(随着 r 的增加会稍微慢一些?),而在 Python 3 中则快得多。
  • 认真的吗?没有标准库可以做到这一点,比如 numpy 等?
  • @CharlieParker,在许多环境中安装 numpy 并非易事。另外,为什么要为这么简单的问题费这么大的力气?
  • 如果你想处理不可能的场景(r n),然后:if r < 0: return 0 在将 r 重置为最小值后。
【解决方案2】:

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

【讨论】:

  • 是的,但这会慢得多。
  • 请参阅stackoverflow.com/questions/3025162/… 以获得更好的答案,例如scipy.comb 或 gmpy.comb。
  • 对于“慢”的一些定义。如果计算扑克赔率是完全可以接受的。 OP没有指定。
  • @Renato:你在说什么?这个答案一点也不危险。你认为math.factorial 返回一个浮点数,而不是一个任意精度的整数吗?
  • 在我的系统上,计算 10000 C 500 需要 10 毫秒,并返回 861 位数字的答案。准确而且不是特别“慢”:^)
猜你喜欢
  • 1970-01-01
  • 2011-04-08
  • 2019-01-18
  • 1970-01-01
  • 2022-01-14
  • 2020-02-13
  • 1970-01-01
  • 2017-05-07
  • 2015-10-16
相关资源
最近更新 更多