Python math.perm() 方法用于计算按特定顺序从一组 “n” 个不同项目中选择的 “k” 项的排列数。在数学上,它表示为 -
P(n,\:k)\:=\:\frac{n!}{(n\:-\:k)!}
哪里,n!表示 “n” 的阶乘,它是从 1 到 n 的所有正整数的乘积,并且 (n−k)!表示 (n-k) 的阶乘。
例如,如果你有一组 “5” 个不同的项目,并且你想排列其中的 “3” 个,那么 “math.perm(5, 3)” 将返回排列的数量,即 5!/(5-3)!= 5!/2!= 5 × 4 × 3 × 2 × 1/2 × 1 =60。
语法
以下是 Python math.perm() 方法的基本语法 -
math.perm(n, k)
参数
此方法接受以下参数 -
- x − 它是项或元素的总数。
- y −它是要排列的项目数 (排列)。
返回值
该方法返回给定值 “n” 和 “k” 的排列。
示例 1在下面的示例中,我们正在计算从一组 “5” 个不同元素中选择 “3” 个元素的排列数量 −
import math
result = math.perm(5, 3)
print("The result obtained is:",result)
输出
获得的输出如下 -
The result obtained is: 60
示例 2
在这里,我们正在计算从一组 “4” 元素中选择 “2” 元素的排列次数,并允许替换 -
import math
result = math.perm(4, 2)
print("The result obtained is:",result)
输出
以下是上述代码的输出 -
The result obtained is: 12
示例 3
现在,我们正在计算排列单词 “MISSISSIPPI” 的字母的排列次数,同时考虑重复的字母 -
import math
word = "MISSISSIPPI"
n = len(word)
result = math.perm(n)
print("The result is:",result)
输出
我们得到的输出如下所示 -
The result is: 39916800
示例 4
在这个例子中,我们正在计算从空集中选择 “0” 元素的排列次数 -
import math
result = math.perm(0, 0)
print("The result obtained is:",result)
输出
生成的结果如下所示 -
The result obtained is: 1