使用python计算多项式_Python是否具有计算多项式系数的函数?

I was looking for a Python library function which computes 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.

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?

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).

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, 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.

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值