Python math.comb() Method

Python math 模块Python math Module

Python math.comb(n, k)Used to calculate the number of combinations, which represents the total number of ways to select k elements from n distinct elements.

The parameters passed must be positive integers.

Python version: 3.8

Syntax

The syntax of the math.comb() method is as follows:

math.comb(n, k)

Parameter description:

  • n-- Required, positive integer number.
  • k-- Required, positive integer number.

Return Value

Returns an integer representing the total number of combinations, returning the number of ways to select k elements from n distinct elements.

Example

The following example returns the total number of ways to select 5 items from 7 items:

Example

# Import the math package
import math

# Initialize the number of items available for selection
n = 7

# Initialize the number of possible choices available
k = 5

# Total number of combinations for selecting 5 items from 7 items
print (math.comb(n, k))

Output result:

21

Python math 模块Python math Module

Other Extensions