数学模块Python中的Math库包含许多数学运算,可以使用该模块轻松执行。math.perm()Python中的method方法用于获取从n个项中选择k个项(不重复且有序)的方法数量。评估为n! /(n-k)!当k <= n时,当k> n时为0。此方法是Python版本3.8中的新增功能。
用法: math.perm(n, k = None)
参数:
n:非负整数
k:一个非负整数。如果未指定k,则默认为None
返回:一个整数值,表示从n个项目中选择k个项目(不重复且有序)的方式。如果k为none,则方法返回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