Python – math.perm() 方法
Python中的数学模块包含许多数学运算,可以使用该模块轻松执行。 Python中的math.perm()
方法用于获取从 n 个项目中选择 k 个项目的方法数,不重复且有顺序。它评估为n! /(n - k)!当k <= n时,当k > n时计算为 0。
此方法是Python 3.8 版中的新方法。
Syntax: math.perm(n, k = None)
Parameters:
n: A non-negative integer
k: A non-negative integer. If k is not specified, it defaults to None
Returns: an integer value which represents the number of ways to choose k items from n items without repetition and with order. If k is none, method returns n!.
代码 #1:使用math.perm()
方法
# Python Program to explain math.perm() 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 with order
nPk = math.perm(n, k)
print(nPk)
n = 5
k = 3
# Get the number of ways to choose
# k items from n items without
# repetition and with order
nPk = math.perm(n, k)
print(nPk)
输出:
90
60
代码 #2:当 k > n
# Python Program to explain math.perm() method
# Importing math module
import math
# When k > n
# math.perm(n, k) returns 0.
n = 3
k = 5
# Get the number of ways to choose
# k items from n items without
# repetition and with order
nPk = math.perm(n, k)
print(nPk)
输出:
0
代码 #3:如果未指定 k
# Python Program to explain math.perm() method
# Importing math module
import math
# When k is not specified
# It defaults to n and
# math.perm(n, k) returns n ! n = 5
nPk = math.perm(n)
print(nPk)
输出:
120
参考: Python数学库