Python math.comb() Method



The Python math.comb() method is used to calculate the number of combinations of "k" items chosen from a set of "n" items, where order does not matter, and repetition is not allowed.

Mathematically, the number of combinations is represented by the binomial coefficient, often denoted as C(n,k), and is calculated using the formula −

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

Where,

  • n is the total number of items in the set.
  • k is the number of items to be selected from the set.
  • n! represents the factorial of n, i.e. the product of all positive integers up to n.

Syntax

Following is the basic syntax of the Python math.comb() method −

math.comb(n, k)

Parameters

This method accepts the following parameters −

  • n − This is an integer representing the total number of items.

  • k − This is an integer representing the number of items to choose.

Return Value

The method returns an integer value representing the number of combinations of choosing k items from n items.

Example 1

In the following example, we are calculating the number of combinations of 2 items chosen from a set of 5 items −

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

Output

The output obtained is as follows −

The result obtained is: 10

Example 2

Here, we are calculating the number of combinations of 0 items chosen from a set of 6 items, which equals 1. This is because there is only one way to choose zero items from a set −

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

Output

Following is the output of the above code −

The result obtained is: 1

Example 3

In this example, we use variables "n" and "k" to represent the number of items in the set and the number of items to choose, respectively. We then calculate the number of combinations accordingly −

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

Output

We get the output as shown below −

The result obtained is: 56

Example 4

The math.comb() method automatically retrieves the result as an integer, even if the arguments are fractional.

Now, we calculate the number of combinations of 2 items chosen from a set of 7 items −

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

Output

The result produced is as shown below −

The result obtained is: 21
python_maths.htm
Advertisements