Python math.perm() 方法



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
python_maths.htm
廣告