Python math.comb() 方法



Python 的 math.comb() 方法用於計算從包含 "n" 個專案的集合中選擇 "k" 個專案的組合數,其中順序無關緊要,並且不允許重複。

在數學上,組合數由二項式係數表示,通常表示為 C(n,k),並使用以下公式計算:

C(n,k) = n!/k!(n-k)!

其中,

  • n 是集合中專案的總數。
  • k 是要從集合中選擇的專案數。
  • n! 表示 n 的階乘,即從 1 到 n 的所有正整數的乘積。

語法

以下是 Python math.comb() 方法的基本語法:

math.comb(n, k)

引數

此方法接受以下引數:

  • n - 這是一個整數,表示專案的總數。

  • k - 這是一個整數,表示要選擇的專案數。

返回值

該方法返回一個整數,表示從 n 個專案中選擇 k 個專案的組合數。

示例 1

在以下示例中,我們計算從包含 5 個專案的集合中選擇 2 個專案的組合數:

import math
result = math.comb(5, 2)
print("The result obtained is:",result)

輸出

獲得的輸出如下:

The result obtained is: 10

示例 2

在這裡,我們計算從包含 6 個專案的集合中選擇 0 個專案的組合數,它等於 1。這是因為只有一種方法可以從集合中選擇零個專案:

import math
result = math.comb(6, 0)
print("The result obtained is:",result) 

輸出

以下是上述程式碼的輸出:

The result obtained is: 1

示例 3

在此示例中,我們使用變數 "n" 和 "k" 分別表示集合中專案的數量和要選擇的專案的數量。然後,我們相應地計算組合數:

import math
n = 8
k = 3
result = math.comb(n, k)
print("The result obtained is:",result) 

輸出

我們得到如下所示的輸出:

The result obtained is: 56

示例 4

math.comb() 方法會自動將結果檢索為整數,即使引數是小數。

現在,我們計算從包含 7 個專案的集合中選擇 2 個專案的組合數:

import math
result = math.comb(7, 2)
print("The result obtained is:",result) 

輸出

產生的結果如下所示:

The result obtained is: 21
python_maths.htm
廣告