Python 二项式系数 [英] Python Binomial Coefficient

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

问题描述

import math
x = int(input("Enter a value for x: "))
y = int(input("Enter a value for y: "))

if y == 1 or y == x:
    print(1)

if y > x:
    print(0)        
else:
    a = math.factorial(x)
    b = math.factorial(y)
    div = a // (b*(x-y))
    print(div)  

这个二项式系数程序有效,但是当我输入两个相同的数字时,应该等于 1,或者当 y 大于 x 时,它应该等于 0.

This binomial coefficient program works but when I input two of the same number which is supposed to equal to 1 or when y is greater than x it is supposed to equal to 0.

推荐答案

这个问题很老了,但是当它出现在搜索结果的高位时,我会指出 scipy 有两个计算二项式的函数系数:

This question is old but as it comes up high on search results I will point out that scipy has two functions for computing the binomial coefficients:

  1. scipy.special.binom()
  2. <代码>scipy.special.comb()

import scipy.special

# the two give the same results 
scipy.special.binom(10, 5)
# 252.0
scipy.special.comb(10, 5)
# 252.0

scipy.special.binom(300, 150)
# 9.375970277281882e+88
scipy.special.comb(300, 150)
# 9.375970277281882e+88

# ...but with `exact == True`
scipy.special.comb(10, 5, exact=True)
# 252
scipy.special.comb(300, 150, exact=True)
# 393759702772827452793193754439064084879232655700081358920472352712975170021839591675861424

请注意,scipy.special.comb(exact=True) 使用 Python 整数,因此它可以处理任意大的结果!

Note that scipy.special.comb(exact=True) uses Python integers, and therefore it can handle arbitrarily large results!

速度方面,三个版本给出的结果有些不同:

Speed-wise, the three versions give somewhat different results:

num = 300

%timeit [[scipy.special.binom(n, k) for k in range(n + 1)] for n in range(num)]
# 52.9 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit [[scipy.special.comb(n, k) for k in range(n + 1)] for n in range(num)]
# 183 ms ± 814 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)each)

%timeit [[scipy.special.comb(n, k, exact=True) for k in range(n + 1)] for n in range(num)]
# 180 ms ± 649 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

(对于 n = 300,二项式系数太大而无法使用 float64 数字正确表示,如上所示).

(and for n = 300, the binomial coefficients are too large to be represented correctly using float64 numbers, as shown above).

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

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