Python是否具有计算多项式系数的函数? [英] Does Python have a function which computes multinomial coefficients?

查看:565
本文介绍了Python是否具有计算多项式系数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找能够计算多项式系数的Python库函数。

I was looking for a Python library function which computes multinomial coefficients.

我在任何标准库中都找不到任何这样的函数。
对于二项式系数(其中多项式系数是一个概括),存在 scipy.special.binom 以及 scipy.misc.comb 。另外, numpy.random.multinomial 从多项式分布中抽取样本,然后 sympy.ntheory.multinomial.multinomial_coefficients 返回与多项式系数有关的字典。

I could not find any such function in any of the standard libraries. For binomial coefficients (of which multinomial coefficients are a generalization) there is scipy.special.binom and also scipy.misc.comb. Also, numpy.random.multinomial draws samples from a multinomial distribution, and sympy.ntheory.multinomial.multinomial_coefficients returns a dictionary related to multinomial coefficients.

但是,我没有找到合适的多项式系数函数,给出了 a,b,...,z 返回(a + b + ... + z)!/(a!b!... z!)。我错过了吗?有没有充分的理由吗?

However, I could not find a multinomial coefficients function proper, which given a,b,...,z returns (a+b+...+z)!/(a! b! ... z!). Did I miss it? Is there a good reason there is none available?

我很乐意为SciPy做出有效的实施。 (我必须弄清楚如何做出贡献,因为我从未做过。)

I would be happy to contribute an efficient implementation to SciPy say. (I would have to figure out how to contribute, as I have never done this).

对于背景,在扩展(a + b + ... + z)^ n。此外,他们还计算了将 a + b + ... + z 个不同的对象存放到不同的容器中的方式,以便第一个容器包含一个对象,等等。有时我会因欧拉计划问题而需要它们。

For background, they do come up when expanding (a+b+...+z)^n. Also, they count the ways of depositing a+b+...+z distinct objects into distinct bins such that the first bin contains a objects, etc. I need them occasionally for a Project Euler problem.

BTW,其他语言也提供此功能: Mathematica MATLAB 枫叶

BTW, other languages do offer this function: Mathematica, MATLAB, Maple.

推荐答案

要部分回答我自己的问题,下面是我对多项式函数的简单而高效的实现:

To partially answer my own question, here is my simple and fairly efficient implementation of the multinomial function:

def multinomial(lst):
    res, i = 1, 1
    for a in lst:
        for j in range(1,a+1):
            res *= i
            res //= j
            i += 1
    return res

到目前为止,从注释看来,在任何标准库中均不存在该函数的有效实现。

It seems from the comments so far that no efficient implementation of the function exists in any of the standard libraries.

更新(2020年1月)。正如Don Hatch在评论中指出的那样,可以通过寻找最大的论点来进一步改善(尤其是在它主导所有其他情况的情况下):

Update (January 2020). As Don Hatch has pointed out in the comments, this can be further improved by looking for the largest argument (especially for the case that it dominates all others):

def multinomial(lst):
    res, i = 1, sum(lst)
    i0 = lst.index(max(lst))
    for a in lst[:i0] + lst[i0+1:]:
        for j in range(1,a+1):
            res *= i
            res //= j
            i -= 1
    return res

这篇关于Python是否具有计算多项式系数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆