Python – math.comb() 方法
Python中的数学模块包含许多数学运算,可以使用该模块轻松执行。 Python中的math.comb()
方法用于获取从 n 项中选择 k 项的方法数,无需重复且无顺序。它基本上评估为n! / (k! * (n – k)!)当 k n。它也被称为二项式系数,因为它等价于表达式 (1 + x) n的多项式展开中的第 k 项系数。
此方法是Python 3.8 版中的新方法。
Syntax: math.comb(n, k)
Parameters:
n: A non-negative integer
k: A non-negative integer
Returns: an integer value which represents the number of ways to choose k items from n items without repetition and without order.
代码 #1:使用math.comb()
方法
# Python Program to explain math.comb() method
# Importing math module
import math
n = 10
k = 2
# Get the number of ways to choose
# k items from n items without
# repetition and without order
nCk = math.comb(n, k)
print(nCk)
n = 5
k = 3
# Get the number of ways to choose
# k items from n items without
# repetition and without order
nCk = math.comb(n, k)
print(nCk)
输出:
45
10
代码 #2:当 k > n
# Python Program to explain math.comb() method
# Importing math module
import math
# When k > n
# math.comb(n, k) returns 0.
n = 3
k = 5
# Get the number of ways to choose
# k items from n items without
# repetition and without order
nCk = math.comb(n, k)
print(nCk)
输出:
0
代码#3:使用math.comb()
方法在表达式 (1 + x) n的二项式展开中找到第 k 项的系数
# Python Program to explain math.comb() method
# Importing math module
import math
n = 5
k = 2
# Find the coefficient of k-th
# term in the expansion of
# expression (1 + x)^n
nCk = math.comb(n, k)
print(nCk)
n = 8
k = 3
# Find the coefficient of k-th
# term in the expansion of
# expression (1 + x)^n
nCk = math.comb(n, k)
print(nCk)
输出:
10
56
参考: Python数学库